Executor service in java--> how to convert single thread code to use executor
executorservice, java, multithreading, threadpool
Solution
In your main, you can write something like this:
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
executor.submit(new Runnable() {
String taskSnap = task.toString();
public void run() {
try {
println(task.run(null));
} catch( InterruptedException e) {
println("ITC - " + taskSnap + " interrupted ");
}
}
});
The submit method will execute the Runnable on one of the threads within the executor service.
Note: Don't forget to shutdown the executor service when you don't need it any more or it will prevent your program from exiting.
Problem
Pardon me if the question sounds silly - I am just starting to use Executor. I have an existing java app that uses threads in this manner-- basically standalone threads are used-- ``` private Thread spawnThread( ) { Thread t = new Thread() { String taskSnap = task.toString(); public void run() { try { println( task.run( null ) ); }catch( InterruptedException e ) { println( "ITC - " + taskSnap + " interrupted " ); } } }; return t; } ``` As you can see from above, the function returns a new thread. Now in the main() function of the program, a new thread is created in this manner-- ``` taskThread = spawnThread(); taskThread.start(); ``` What i want to do is, create an executor service (with fixed number of threads)--> and then hand off creation of new thread/execution of task by the new thread to that executor. As I am very new to Executor, what I wish to know is, how do I change the above code so that instead of a new separate thread being formed, a new thread is instead created within the thread pool. I cannot see any command to create a thread (within the thread pool)--> hand off the above task to that thread (and not to a stand-alone thread as above). Please let me know how to resolve this problem.