LunaVulpo
LunaVulpo

Reputation: 3211

How to have java executor with same thread?

For some proposes, I need to create an Executor which has always one same thread.

Executors.newFixedThreadPool(1);
Executors.newScheduledThreadPool(1);

Above examples create one thread pool but when work is done then the thread will be ended and again created a new one if a new task is passed to the executor.

So I figured out something like this:

new ThreadPoolExecutor(1,1,Long.MAX_VALUE, TimeUnit.DAYS, new LinkedBlockingQueue<>());

it seems that works but I have doubts if it's the right approach. Can someone show a better/correct way?

Upvotes: 2

Views: 1089

Answers (1)

Andrew
Andrew

Reputation: 49606

Executors.newSingleThreadExecutor();

From the documentation (emphasis mine):

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

Upvotes: 3

Related Questions