views:

247

answers:

2

hi, i am facing a problem regarding the thread. I am having a class which implements runnable, and i can use thread.start() method on that class. My question is i have one more class java.util.concurrent.ExecutorService in which i can call executor.submit(thread)..

can anyone please tell me what is the difference between thread.start() and executor.submit(thread)...

+2  A: 

The executor.submit method takes a Runnable, not a Thread. The point of executorServices is that they take control over creating and pooling threads so the code calling them doesn't have to.

Nathan Hughes
+1  A: 

You should not submit a thread to an executor. First it is simply a waste because the only method that will be called on it is run(), and you just need a Runnable and don't need a Thread for that.

Secondary, while this issue is solved in the latest JDK, it used to be the case that a memory leak problem occurs if you create a lot of Thread objects and don't call .start() on them. Basically creating a Thread objects allocates some memory that can only be reclaimed after .start() was called. Therefore, doing executor.submit(thread) is potentially hazardous in earlier JDKs (I think it was only solved in JDK6 or so).

Coming back to your question, executor.submit(thread) is not valid.. It is simply wrong, because an executor uses its own thread to execute the runnable. That's after all the whole point of using a executor. You want to separate task (invocation) and execution. Only if you want to supply the executor (thread), you should be using Thread, but it is rare that you need to do so. Generally it is advisable to implement a Runnable and use executors to execute it, rather than dealing with Thread yourself.

Enno Shioji