For conventional Producer-Consumer problem, we can use ExecutorService as queue. What are disadvantages of it? Is it less efficient? Because creation of thread is costly.
executor = Executors.newFixedThreadPool(90);
// This will be called many times concurrently
public void processObjectsWithFixedSetOfThreads(Foo objectToProcess) {
//Create a new thread and submit (executor is of fixed size hence extra tasks will be queued)
executor.submit(new ObjectProcessorWorker(objectToProcess));
}
class ObjectProcessorWorker implements Runnable() {
public ObjectProcessorWorker(Foo obj) {
this.obj = obj;
}
public void run() {
longRunningProcess(obj);
}
}
Why BlockingQueue is recommended for Producer-Consumer problem however it can be done without that too (As shown above)?
EDIT
Many people are not getting the difference because ThreadPoolExecutor internally maintains the BlockingQueue.
In a biscuit factory there is a task of wrapping biscuits. If I am its owner I have two ways to speed up wrapping task.
Put biscuits and wrapper on assembly line have 10 workers doing work of wrapping.
I ->
queue.put(biscuits, wrapper)
Worker ->
queue.take()
Creating a task of wrapping biscuits putting it on a assembly line, and let the 10 workers do that.
I ->
new Task(biscuits, wrapper)
Worker ->
task = queue.take(); do(task);
I am asking the disadvantages of the later one.