views:

65

answers:

5

Does it make sense to use a ThreadPool with a poolsize of just 1 to basically just recycle that one thread over and over again for different uses in the application? Rather then doing new Thread(Runnable()) etc and then letting the garbage collector handle the removal of the thread, I thought it would be more efficient to just use that one thread for different jobs that dont need to run together.

This is what I am currently doing to define 1 poolsize threadpool.

    private static int poolSize = 1;
private static int maxPoolSize = 1;
private static long keepAliveTime= 10;
private static final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100);
private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);
+1  A: 

With new Thread(Runnable) you can execute N threads concurrently. It may be an advantage, but it also may bring synchronization issues.

With reusing one Thread you lose the ability to execute tasks in parallel, but you are spared the sync/concurrency issues.

Konrad Garus
Well in the program Im making API calls a lot and parsing JSON, however I dont need to make parallel calls (i.e multiple api calls at once, which is why i resorted to this technique).
Faisal Abid
+1  A: 

There is nothing wrong with a single threaded thread pool if it fits with how you application should function. For example, in an application I work on we have a number of services where we need to ensure that data is strictly processed in order of arrival. To do this we simply execute tasks on a single threaded executor.

Also using Executors means that it is easy to adjust the thread pool parameters in the future if you need to.

Mark
Thanks for your comments! Im confident in what i am doing now.Thanks to everyone to commented as well!
Faisal Abid
+1  A: 

Defining a one-thread pool this way is perfectly compatible with modern coding standards. it has the only drawback of not letting you parallelize any fragment of yhe code. However, I guess that's what you wanted.

Riduidel
+1  A: 

One of the advantage of using the ThreadPoolExecutor being that once the thread is created, it will get reused as against creation of new Thread everytime when using new Thread.

Tushar Tarkas
+1  A: 

Have you tried it without a Thread ? Threads are no efficient unless really needed and you need to do a lot of I/O specific stuff in parallel. If what you are looking for is a simple internal message queue, then it is fine.

Romain Hippeau