Reputation: 289
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);
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.
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);
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
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:
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
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