Have a question waiting condition

In the GUI, I have several buttons. These buttons disable workflows that send requests over the network to the server. In a separate thread there is a listener that receives responses from the server. This response is passed to the same object that worker threads execute methods through the Observer / Observable interface.

I need to make workflows wait for a response from the server that belongs to them. Essentially, the worker thread must send a command, and then wait for some condition indicating the correct answer. I can think of several ways to do this (hibernation, polling, waiting, notification, monitors, etc.), but is there any specific method that would be better in this situation?

+7
source share
2 answers

I would recommend using the high-level locking mechanism from the java.util.concurrent package. For example, CountDownLatch - "Synchronization help, which allows one or more threads to wait for the completion of a set of operations in other threads."

+6
source

This is not like the place you want to block at all. You are already in the workflow, so you do not hold any state for your GUI or anything else, I would send a message and a guarantee - when your answer comes back, take another thread from the pool and send it is fun.

If you have data that is shared between them, put them in your own object in the collection associated with some common value, and add a new stream when it appears.

For readability / simplicity, the data object should also contain code that knows how to process this data, so all you have to do when you receive an incoming message is to get a key that uniquely identifies which object sent it , get this object by key and call this method "Data Received", passing the information you received from the package.

The good thing is that it is trivial for a simple listener to process a huge number of incoming packets by creating the Received Data method, which can implement many different handlers.

OO is cool, eh?

+2
source

All Articles