4

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?

Kehaar
  • 77
  • 4
  • 2
    **NO**. Having waiting threads is exactly what you should do. Having waiting threads is (almost) free. Having _spinning_ threads isn't. WebServers like Tomcat can have literally hundreds of waiting threads. – Boris the Spider Jul 10 '14 at 13:05
  • 2
    One thread doing this, no, ten thousand thread doing this is a bad idea. As a very rough guide, each thread which runs rarely has an overhead of about 0.05% of 1 CPU. – Peter Lawrey Jul 10 '14 at 13:09
  • Great. There's only going to be a handful of these threads on different queues. Thanks for the help. – Kehaar Jul 10 '14 at 13:22
  • 1
    Waiting is the purpose for which threads originally were invented. Threads have been around since long before most computers had more than one processor. Multi-threading was a way to simplify applications that had to wait for more than one different thing: An app with ten threads waiting each waiting for one kind of event/input was often easier to understand than a single-threaded app with one big event-processing loop that dispatched to ten different handlers. – Solomon Slow Jul 10 '14 at 15:51

1 Answers1

5

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

LionC
  • 3,106
  • 1
  • 22
  • 31