I have the following design:
There is a Task which extends TimerTask and it is scheduled to run every minute.
This Task will try to take items from a central queue (as a single consumer) and write their representation into a file.
Additionally, there are multiple producers which put items into the central queue from time to time.
I am interested that each time the Task is executed (run() method executed) it will extract all the items from the queue if there are items, if there are no items do nothing.
Producers should sleep on the Queue if it is full.
My Solution for this problem is:
Create ExtractTask which extends TimerTask.
ExtractTask will contain a BlockingQueue.
Each producer will receive a reference to the queue instance by executing method getQueue().
Producers will execute BlockingQueue.put() method.
The consumer will execute BlockingQueue.poll() method inside run().
Can you suggest a better design? does my design contain any problematic scenario cases? any synchronization problems this design may encounter?
I would:
Other than that you’ve got it.
If you’re willing to risk a dependency on Spring you should look into Spring Integration. All the components you describe are in there. You could also solve the problem using many other frameworks, like Camel or Akka; my main point here is to not maintain this code yourself if you don’t absolutely have to.
Disclaimer: I’m somewhat biased about Spring Integration