Reputation: 35
Basically, I have a graphical swing application. I need to use UDP to send and receive data, but I don't want any receive(packet) calls in the application's code. I decided to run the receiving end of the program on a separate thread. The thread has an int field that gets updated to the value from incoming packets. How would I get the value of this field from the thread. Can I just call the get method for the field, or do I have to interrupt the thread first?
Upvotes: 1
Views: 440
Reputation: 9584
You have just 1 objective here. UI should not wait and hang for data on the network. You need a LinkedList (not a ArrayList), a dataJustArrived method, that notifies your LinkedList object. A thread that is running in a while (true), and waiting on LinkedList.
dataJustArrived, add's the data object to the linked list and notifies the wait. The wait unlocks, and checks if linkedList.lenght > 0, and removes (not GETS's, but removes) the data from the list and processes the UI.
Important points
before you wait, check if dataList.lenght > 0, why wait if there is data to process right ?
public synchronized void dataJustArrived(Object data) {
synchronized (dataList) {
dataList.addLast(data);
this.notify();
}
}
public void run() {
Object data ;
while (true) {
synchronized (this) {
if (dataList.isEmpty()) {
try {
dataList.wait();
} catch (InterruptedException ignored) {
ignored.printStackTrace();
}
}
if (!dataList.isEmpty)
data = dataList.removeFirst();
//
// Process your UI here
//
}
}
}
Upvotes: 0
Reputation: 7952
Although the GUI thread can read the int getter safely (assuming appropriate synchronization or volatile variable), consider taking the time to use SwingWorker as it will make your app more responsive. Basically you replace your custom thread with a SwingWorker object. The code you now have in run()
goes in SwingWorker.doInBackground()
.
You start the worker and the doInBackground
code executes in a separate thread. Presumably this is a UDP receive loop. When your loop receives an new int, you call publish
(still in the background thread). This will cause another SwingWorker method process
(which you have overridden with some custom code) to be called in the event thread. Here you can safely update your GUI because you are running in the event thread.
This eliminates the need to create timers to poll getter of the UDP thread. The UI is more responsive because the receive -> publish -> process sequence is pretty quick.
Upvotes: 1