I was reading a little on producer consumer implementation in Java. Most of the online code exampled showed the solution with the following basic object:
A blocking queue to use as the data pipe
n number of Producer which pushed messaged into the Queue
n number of consumer which are polling for data from the queue
Normally the consumers are submitted to a thread pool which completes the implementation.
Another option I investigated, that had little to none representation online is simply submitting the task as a runnable object to a FixedThreadPool.
In this implementation, the business logic for handling a message is implemented in a run()
method of a Runnable object. When we have a new message we would like to process we can simply submit a new task of that type to a FixedThreadPool
, and... that's it. The number of running threads is managed by the FixedThreadPool
implementation along with the logic of polling for messages, all that is left for us to implement is the buisness logic for our use case.
Can anyone explain why is this solution overlooked?
Is there any specific reason we need to use a blocking queue and polling when the java language already implemented that for us?
public class ProducerConsumerExample{
private ExecutorService pool;
public ProducerConsumerExample(int numberOfThreads){
this.pool = Executors.newFixedThreadPool(numberOfThreads);
}
public void submit(MessageObject msg){
pool.submit(new MessagePrinter(msg));
}
}
public class MessagePrinter implements Runnable{
private MessageObject msg;
public MessagePrinter(MessageObject msg){
this.msg = msg;
}
@Override
public void run() {
//only need to implement logic that is releavent for our use case
System.out.println("Message recieved " + msg.toString());
}
}
public static void main(String[] args){
ProducerConsumerExample ex = new ProducerConsumerExample(5);
for(int i=0;i<WHATEVER;i++){
ex.submit(new MessageObject());
}
}
ThreadFactory
interface, and ways to get a system-defaultThreadFactory
. Check it out! – Solomon Slow