I'm trying my hand at multithreading in java, something I have never done before. The pet application I'm trying to design at the moment has one Blocking Queue and several Workers. The application follows these rules:
The application is supposed to exit if:
Basically, once all messages are consumed and no more messages are being produced/present in the system, I'm expected to exit. The application is guaranteed to reach this point eventually.
Now my question, I'm not sure what's the best practice/design to understand when the above conditions are true avoiding racing conditions. Any help?
I'm currently at design stage, so I don't have code to show you, sorry about that (I know my question at this point is quite generic, so feel free to ask me any question). Any advice is welcome!
Thanks in advance!
One way to do it would be for each worker to add 1 to an AtomicInteger when it starts (representing that it is working) and then subtract 1 when it ends. After it subtracts 1, if the AtomicInteger is 0, this means that there are no “active” workers.
So when a worker ends, it will Subtract 1 from the atomicInteger and then check If the queue size is zero (no waiting messages) and the atomic integer is zero (no active workers), you can quit the application.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.