Santrupta Dash
Santrupta Dash

Reputation: 289

What is benefit of SingleThreadPool over synchronization?

I was studing about ExecutorService. I found that there are 4 types of Thread pools.
1. FixedThreadPool

int coreCount = Runtime.getRuntime().availableProcessors();  
ExecutorService service = Executors.newFixedThreadPool(coreCount);
  1. CachedThreadPool
ExecutorService service = Executors.newCachedThreadPool();

here threads are automatically created if no created thread is free and deleted when a thread is idle by JVM. Threads are stored in queue.

  1. ScheduledThreadPool
    Threads are stored in a delay queue this queue can sort the element based on their scheduled occurrence.

Service.schedule
Service.scheduleAtFixedRate
Service.scheduleAtFixedDelay

Schedule the tasks to run based on time delay (and retrigger for fixedRate / fixedDelay)
Life Cycle: More threads are created if required.

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool ( 10);
// task to run after 10 second delay
scheduledExecutorService.schedule(new Task(),  10, TimeUnit.SECONDS);

// task to run repeatedly every 10 seconds
scheduledExecutorService.scheduleAtFixedRate(new Task(),  15,  10, TimeUnit.SECONDS);

// task to run repeatedly 10 seconds after previous task completes
scheduledExecutorService.scheduleWithFixedDelay(new Task(),  15,  10, TimeUnit.SECONDS);
  1. SingleThreadedExecutor
    when you require to run thread in a sequential order you should use SingleThreadPoolService.
ExecutorService service = Executors.newSingleThreadExecutor(); 

So my question is the single Thread Executor looks very similar to Synchronized operations. Can anyone please describe any difference between those two. any benefit over synchronization. What was the motivation for a Single Thread executor ? means why thread at all ?

Upvotes: 0

Views: 258

Answers (2)

gdomo
gdomo

Reputation: 2052

You can implement analog of single thread executor with a Thread and some synchronized code, however it would take lots of effort. For example, some things you have to implement manually:

  1. A queue of tasks. Task submission (not execution) to an executor would be performed immediately, task would be stored for later execution. Every call to synchronized block would wait, so you have to store task manually in order to archive similar behaviour.
  2. Order of task execution.
  3. Task submission to an executor returns a Future

So look at a executors API and think how could you implement it manually and you see a lot of work to do.

Upvotes: 1

shailb
shailb

Reputation: 164

SingleThreadExecutor makes sure all requests gets executed by a single thread. Imagine a physical kiosk taking orders from customers in queue.

Upvotes: -1

Related Questions