2

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?

1
  • I can understand why you might be concerned about the overhead of destroying and re-creating the worker thread, but why does the identity of the worker thread matter to your application? Commented Sep 13, 2018 at 12:48

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

@LunaVulpo it guarantees that a single thread will be utilised until the first failure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.