Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid 100% CPU utilization without removing while(true)

I am working on a system where I need a while(true) where the loop constantly listens to a queue and increments counts in memory.

The data is constantly coming in the queue, so I cannot avoid a while(true) condition. But naturally it increases my CPU utilization to 100%.

So, how can I keep a thread alive which listens to the tail of queue and performs some action, but at the same time reduce the CPU utilization to 100%?

like image 512
zengr Avatar asked Aug 12 '26 14:08

zengr


2 Answers

Blocking queues were invented exactly for this purpose.

Also see this: What are the advantages of Blocking Queue in Java?

like image 139
lbalazscs Avatar answered Aug 15 '26 04:08

lbalazscs


usually a queue has a way to retrieve an item from it and your thread will be descheduled (thus using 0% cpu) until something arrives in the queue...



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!