Home  >  Core Java

Example of newSingleThreadExecutor in Java

By Arvind Rai, March 04, 2013
newSingleThreadExecutor() returns ExecutorService with one thread pool size. ExecutorService uses single thread to execute the task. Other task will wait in queue. If thread is terminated or interrupted, a new thread will be created. ExecutorService guarantees to finish the task if not shutdown. Same task can be performed by Executors.newFixedThreadPool(1). We will discuss differences later here.

Now let's see how to use newSingleThreadExecutor().
final ExecutorService exService = Executors.newSingleThreadExecutor();
Find the complete example.
NewSingleThreadExecutorTest.java
package com.concretepage;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class NewSingleThreadExecutorTest {
    public static void main(final String... args) throws InterruptedException, ExecutionException {
        // creates thread pool with one thead
        final ExecutorService exService = Executors.newSingleThreadExecutor();
        // callable thread starts to execute
        final Future<Integer> callFuture = exService.submit(new NewSingleThreadExecutorTest().new CallableThread());
        // gets value of callable thread
        final int callval = callFuture.get();
        System.out.println("Callable:" + callval);
        // checks for thread termination
        final boolean isTerminated = exService.isTerminated();
        System.out.println(isTerminated);
        // waits for termination for 30 seconds only
        exService.awaitTermination(30, TimeUnit.SECONDS);
        exService.shutdownNow();
    }
    // Callable thread
    class CallableThread implements Callable<Integer> {
        @Override
        public Integer call() {
            int cnt = 0;
            for (; cnt < 5; cnt++) {
                System.out.println("call:" + cnt);
            }
            return cnt;
        }
    }
}
Output
call:0
call:1
call:2
call:3
call:4
Callable:5
false 

Difference Between newSingleThreadExecutor() and newFixedThreadPool(1)


Similirity
newSingleThreadExecutor() returns ExecutorService with single thread worker and newFixedThreadPool(1) also returns ExecutorService with single thread worker. In both cases if thread terminates, new thread will be created.

Difference
ExecutorService returned by newSingleThreadExecutor(), can never increase its thread pool size more than one. ExecutorService returned by newFixedThreadPool(1), can increase its thread pool size more than one at run time by setCorePoolSize() of the class ThreadPoolExecutor.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us