Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a work item between threads (Java)

I have two threads. The producer is producing pieces of data (String objects), where the consumer processes these strings. The catch is that my application only needs the most recent data object to be processed. In other words, if the producer managed to produce two strings "s1" and then "s2" then I want the consumer to process only "s2". "s1" can be safely discarded.

Of course there's no problem implementing a class that realizes this behavior, but I want to use a standard mechanism from java.util.concurrent (if such a mechanism exists). Note that SynchronousQueue is not a good solution: the consumer will block when enqueueing "s1" and will not get the chance to produce "s2".

(In short, I am looking for a single-element collection with a blocking remove operation and a non-blocking set operation)

Any ideas?

like image 346
Itay Maman Avatar asked Feb 06 '09 16:02

Itay Maman


People also ask

How do you pass data between threads in Java?

If you want synchronous communication between a main thread and a processing thread, you can use a SynchronousQueue. The idea is that the main thread passes data to the processing thread by calling put() , and the processing thread calls take() . Both are blocking operations.

How do you communicate between two threads?

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: wait() notify() notifyAll()

Can two threads access the same data at the same time?

A data race is a state, in which at least two threads access shared data at the same time, and at least one of the threads is a writer. A critical section is a section of the code, which not more than one thread should access at any point in time.


1 Answers

I think your best answer is probably to use ArrayBlockingQueue, where the producer (you only have one producer, right?) removes any existing element before adding the new element.

Sure, there are race conditions in this implementation: the consumer could start processing an element just before the producer removes it. But those race conditions will always exist, no matter what data structure you use.

like image 198
kdgregory Avatar answered Sep 29 '22 22:09

kdgregory