简体   繁体   中英

Is it bad to have threads waiting in java?

I have a thread that basically contains

while(true) {
  current = BlockingQueue.take();
  results = queryDatabaseWith(current);
  AtomicReference.set( results );
}

Realistically the queue is only ever going to have a few things put on it, but it's important that when things are, the DB queries happen in the correct order. The atomic ref is fine as I only care about the results from the last DB query.

Is it bad practice to have this on a thread, basically waiting all day?

No it is not bad to have waiting threads in general, it is common practice and often the nicest solution.

As the answer is pretty short, just a quick advice: If it is not necessary that your thread reacts immediately , you might consider adding Thread.yield to your infinite waiting loop, depending on the system it is running on this can save some unnecessary CPU-usage. See the Oracle documentation

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