简体   繁体   中英

How to understand if your application has finished computing in a multithreading consumer-producer scenario in Java

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:

  • A worker waits for a message in the queue
  • When a worker gets a message from the queue, it processes it, and may produce more messages that are added back to the queue.
  • Some messages don't generate more messages.
  • The application is started with several messages in the queue.
  • 1 Worker = 1 Thread

The application is supposed to exit if:

  • There are no more messages on the queue
  • All workers are blocked and waiting for a message to be consumed

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM