Arturs Vancans Arturs Vancans - 2 months ago 10
Java Question

Is it bad to use polling in Java?

I have several

ArrayLists
which work as queues of data. Each of the queues is linked to an individual thread which checks if that
ArrayList
has some data in it.

while (array.size == 0) {
// nothing
}

// do stuff with one element of the array
// remove element from array
// and call the loop again


I have done similar things in embedded system programming, but is it safe to use this in Java? The concern is about process power waste by iterating around that while loop very fast.

It could be solved by adding
Thread.sleep(100)
and check every 100ms, but then again - slower response time.

The question is - do I need to add that sleep or I shouldn't be concerned about that?

Any suggestions on safer/better system to check for new data in arrays?

Answer

ArrayList is not a thread safe collection, so if one thread adds data to your list, and another thread tries to retrieve data from the same list, you have no guarantee that the other thread will ever see the added elements.

And busy waiting like what you describe consumes cpu resources unnecessarily.

Since you seem to need a queue, why don't you use one, like ArrayBlockingQueue. It has a take method which will block, without consuming CPU cycles, until an item gets added to the queue. And it is thread safe.