Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an "event-driven" background thread in Java?

I like the simplicity of invokeLater() for sending units of work to the AWT EDT. It would be nice to have a similar mechanism for sending work requests to a background thread (such as SwingWorker) but as I understand it, these do not have any sort of event queueing & dispatch mechanism, which is what invokeLater() depends upon.

So instead, I've ended up giving my background thread a blocking queue, to which other threads send messages, and the thread essentially runs a receive loop, blocking until a message arrives.

That, in fact, might be exactly how one would implement EDT-like behavior in a background thread (or would it?). On the other hand, I like the simplicity of a thread that simply dangles there inertly, processing "work droplets" whenever they happen to be dispatched to it from some unseen Event Dispatching Queue in the sky. Does Java provide a way to create such an "event-driven worker thread"? Or is message-queueing the right way to do this, after all? And in a related vein, are there drawbacks to the invokeLater() technique of message-passing?

like image 716
Chap Avatar asked Oct 11 '22 06:10

Chap


1 Answers

The Producer-Consumer Design Patter (which is what you're employing with your blocking queue) is just a different approach to solving a different class of problems; EDT employs the Worker Design Pattern. Take a look at both design patterns and see which one suits your needs best.

  • The Producer-Consumer pattern is generally used when you have multiple threads executing independent tasks separately.
  • The Worker pattern, employed by the EDT, is used to funnel the result of multiple tasks into a single thread (in this case the GUI thread).

Of course, you can take the Producer-Consumer pattern and achieve similar behavior to the Worker pattern if you have a single queue and a single consumer with multiple producers, but that just highlights the flexibility of design patterns. So the point, again, is that choosing a design pattern is based on what works best for your particular situation- there is no particularly wrong choice when the patterns are flexible enough to accommodate the behavior you desire.

like image 164
Kiril Avatar answered Oct 13 '22 01:10

Kiril