I am working on an application, that processes incoming messages. I am not proficient in java multithreading and I am asking your help, folks. Is there anything wrong with the following app structure.
There is main application class with stopRequested boolean field. And there is internal runnable class that listens for incoming messages and process them. Also there is another thread that sets stopRequested to true.
Is this approach working and reliable, or I am wrong?
Below there is a part of my code:
class ApplicationClass {
// we set this var in another thread
// when it is necessary to stop
private stopRequested = false;
public ApplicationClass() {
// starting message processing thread
(new Thread(new MessageProcessing())).start();
}
private class MessageProcessing implements Runnable {
public void run() {
while (!stopRequested) {
if (getNewMessagesCount() > 0) {
processNewMessages();
}
}
}
}
}
Thank you.
There are a few things to think about.
stopRequestedneeds to be volatile to resolve visibility problems (a thread on another core may not see the change otherwise).getNewMessagesCount()doesn’t block then your while loop will spin and consume the core; this will give you the lowest latency but ties up the entire core.getMessageCount()andprocessNewMessages()are invoked beforeApplicationClassis finished being created. Since the instance ofApplicationClasscould be in an incomplete state you could find a rather nasty bug. (For the same reason you never want to have your code subscribe as a listener to events from a constructor, by the way.) Check out Effective Java for more background on this topic.while (!stopRequested && !Thread.currentThread().isInterrupted())Writing correct concurrent programs is hard. I highly recommend reading Java Concurrency in Practice; it will save you a lot of pain.