[concurrency-interest] ThreadFactory.newThread(Runnable) and user-defined Runnables?

Matthias Ernst matthias at mernst.org
Mon Dec 15 14:46:20 EST 2008


On Mon, Dec 15, 2008 at 7:39 PM, borderline_ocd-er
<javafreelancer at gmail.com> wrote:
> using jdk 1.6.0_04 on win xp/sp 3.
>
> given this implementation of Runnable:
>
> abstract class NamedRunnable implements Runnable{
>
>        private String name;
>
>        public NamedRunnable(String name){
>                this.name = name;
>        }
>
>        protected String getName(){
>                return this.name;
>        }
>
> }
>
>
> how come neither the compiler nor the runtime have a problem with
> either of these uses of NamedRunnable as a legal Runnable
> implementation :
>
>
>                Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
>
>                tasks.add(Executors.callable(new NamedRunnable("Thread X"){
>                        public void run(){...this.getName();...}
>                }));
>
>
>                Thread thread1 = new Thread(new NamedRunnable("Thread Y"){
>                        public void run(){...this.getName();...}
>                });
>
> but the compiler complains about this:
>
>   class NamingThreadFactory implements ThreadFactory {
>
>      public Thread newThread(NamedRunnable runnable){
>              return new Thread(runnable);
>      }
>   }
>
> with the message: "The type NamingThreadFactory must implement the
> inherited abstract method ThreadFactory.newThread(Runnable)"
>
> that is, as far as the "Executors.callable(Runnable)" utility method
> and the "Thread(Runnable)" constructor are concerned, NamedRunnable is
> a legal implementation of Runnable. why does
> "ThreadFactory.newThread(Runnable)" disagree?

Interface ThreadFactory promises to create a Thread for any Runnable.
Your NamingThreadFactory doesn't hold up to that promise. Google
covariant parameter types.


More information about the Concurrency-interest mailing list