The “non-executing executor” code blooper of the day

This is a very recent one, not that hard to spot but I have to admit I had to take a look at the code a couple of times over before realizing what a silly mistake I’d made.

So what I wanted to do is use a simple thread pool, and then I wrote a thread factory so I could make sure the threads I created had names I could recognize while debugging the program. Here’s sort of what the code looked like;

        
ExecutorService pool = Executors.newFixedThreadPool(10,new TFactory(10));

public void doSomething(final String something)
     Runnable workOnSomething= new Runnable() {
          @Override
          public void run() {
               System.out.println("Do " + something);
          }
     };
        
     pool.submit(workOnSomething);
}

public class TFactory implements ThreadFactory {
     int threadCount;

     @Override
     public Thread newThread(Runnable run) {
          return new Thread("MyThreadFactoryThread-" +
          (threadCount++));
     }
}

The problem? My threads weren’t running, if you call doSomething(“test”) you won’t see the corresponding “Do test”. Ever.

Do you see the problem?

OK, like I said this is not a hard one. I used the wrong constructor, and omitted to pass the Runnable run along to the thread. No big lesson to learn here, just to be careful with the constructors.

I guess I could also have focused on using the constructor that takes a runnable, and then set the name using setName() instead of doing it via the constructor. Kind of makes you wonder why have a Thread constructor that didn’t have a Runnable in the first place, since you can’t set it after creating the Thread. Of course the answer to that it can be useful for those times you may want to subclass Thread (which in most cases is not a great idea).

But no excuses, I messed up!

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Comments »

 
 

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>