Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42710

Any difference among Executors.newSingleThreadExecutor() and Executors.newFixedThreadPool(1)

I was wondering, what is the difference among Executors.newSingleThreadExecutor() and Executors.newFixedThreadPool(1)

The below is picked from javadoc

Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

I try the following code below, seems no difference.

package javaapplication5;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author yan-cheng.cheok
 */
public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        //ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
        ExecutorService threadExecutor = Executors.newFixedThreadPool(1);
        threadExecutor.submit(new BadTask());
        threadExecutor.submit(new Task());      
    }

    class BadTask implements Runnable {
        public void run() {
            throw new RuntimeException();
        }
    }

    class Task implements Runnable {
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("[LIVE]");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

Most probably something wrong with my understanding :)

Upvotes: 1

Views: 3988

Answers (1)

Thilo
Thilo

Reputation: 262534

Just like it says:

Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

The difference is (only) that the SingleThreadExecutor cannot have his thread size adjusted later on, which you can do with a FixedThreadExecutor by calling ThreadPoolExecutor#setCorePoolSize (needs a cast first).

Upvotes: 7

Related Questions