Faisal Abid
Faisal Abid

Reputation: 9140

Java ThreadPool with poolsize of 1

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);

Upvotes: 2

Views: 1735

Answers (5)

Romain Hippeau
Romain Hippeau

Reputation: 24375

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.

Upvotes: 1

Tushar Tarkas
Tushar Tarkas

Reputation: 1612

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.

Upvotes: 1

Riduidel
Riduidel

Reputation: 22292

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.

Upvotes: 1

Mark
Mark

Reputation: 29119

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.

Upvotes: 4

Konrad Garus
Konrad Garus

Reputation: 54005

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.

Upvotes: 1

Related Questions