Java BlockingQueue of Size=1?
Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue.
I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want?
Example interface:
public interface Wait<T> {
/**
* If "put" has never been called on this object, then this method will
* block and wait until it has. Once "put" has been called with some T, this
* method will return that T immediately.
*/
public T get() throws InterruptedException;
/**
* @param object The object to return to callers of get(). If called more
* than once, will throw an {@link IllegalStateException}.
*/
public void put(T object);
}
Asked by: Wilson596 | Posted: 23-01-2022
Answer 1
You mean something like SynchronousQueue? Another useful class is Exchanger
Answered by: Emma413 | Posted: 24-02-2022Answer 2
I found code for a class called "ObjectLatch" here: http://forums.sun.com/thread.jspa?threadID=5321141
package jfco.progs;
import java.util.concurrent.CountDownLatch;
/**
* <H1>A Blocking Object Latch</H1> This class implements a blocking object
* latch, that acts as a synchronizer between a producer of an object and it's
* consumer(s).
* <p>
* An object is set with <code>set()</code>only ONCE. Further attempts to set
* the object are just ignored.<br>
* <p>
* Consumers request the object with <code>get()</code>. If the object is not
* already set, consumers are blocked waiting until the object is available or <br>
* until an interrupt (InteruptedException) terminates the wait.
* <p>
* The latch can be tested for object availability with isAvailable(), which
* answers true if the object has already been set. <br>
*/
public class ObjectLatch<R> {
/** The object. */
private R object = null;
/** The latch counter created and set to 1. */
private final CountDownLatch latch = new CountDownLatch(1);
/**
* Checks if the object is already available (has been already set).
*
* @return true, if the object is already available (has been already set)
*/
public boolean isAvailable() {
return latch.getCount() == 0;
}
/**
* Sets the object if it is not already set. Otherwise ignore this request.
*
* @param object
* the object
*/
public synchronized void set(R object) {
if (!isAvailable()) {
this.object = object;
latch.countDown();
}
}
/**
* Get the object if it is already available (has already been set).
* <p>
* If it is not available, wait until it is or until an interrupt
* (InterruptedException) terminates the wait.
*
* @return the object if it is already available (has already been set)
*
* @throws InterruptedException
*/
public R get() throws InterruptedException {
latch.await();
synchronized (this) {
return object;
}
}
}
Answered by: Owen874 | Posted: 24-02-2022
Similar questions
multithreading - Do I need to synchronize my calls to BlockingQueue (java)?
I want to store a list of objects in a thread safe manner, while maintaining priority. Originally I started out using a BlockingQueue for this as it's thread safe and has ability to maintain custom priority.
I'm wondering if I need to synchronize my methods? My code looks like:
void addToQueue(SomeObject obj) {
... put it on my priority queue
... do some logging
}
What I h...
multithreading - java - blockingQueue with condition Issue
I've two threads the first one execute some tasks (called TaskManager)
and the second listen to events and store them in a queue (called EventManager).
EventManager should be woken up and start running only if the queue is not empty and some condition is true.(when EventManager is not currently executing !eventManager.isRunning())
Ex. code:
class TaskManager implements Runnable {
...
multithreading - put(s) and take(s) in BlockingQueue Java
Here is the example.
class Factory {
Queue<Object> queue = new LinkedBlockingQueue<Object>();
public Object consume() {
queue.take();
}
public void produce() {
for (int i = 0; i < 2; i++) {
queue.put(new Object());
}
}
}
For example I have two threads which both called consume(). They are waiting for a producer to put...
multithreading - BlockingQueue inside Transaction java
I am in process of building a system which has a basic Produce Consumer paradigm flavor to it, but the Producer part needs to be a in a Transaction mode.
Here is my exact scenario :
Poller Thread -
[Transaction START]
Polls the DB for say 10 records
* Sets the status in DB for those records as IN-Progress
* Puts the above 10 records in a LinkedBlockingQueue - workqueue
[Transaction END]
Wo...
multithreading - Java BlockingQueue Messages Lagging issue between threads
I have implemented a two player game with thread pool of sockets. each player connects to their own thread. I added a message Queue system according to this article.
Problem is the messages are lagging. the first respond from the first player is added to messageQueue as expected. But second player doesn't received it b...
multithreading - Java BlockingQueue appears to corrupt data during transfer
I have n producer threads feeding 1 consumer thread via BlockingQueue. I am using .put and .take (the latter when .peek != null). This is working fine for at least a dozen messages, except for the invariable data corruption, apparently during transit. Currently I am only instantiating one producer thread.
For example, the producer thread will identify a rectangle and set the object values, which are then s...
multithreading - Java BlockingQueue take() vs poll(time, unit)
I think mistakenly guys compared take() vs poll(), but I found that it is reasonable to compare take() vs poll(time, unit) as both provided by BlockingQueue and both are blocking tell queue not Empty "and in case or poll or time-out", OK lets start comparing, usually I'm using take() for BlockingQueue but I was facing issues about:
handling interrupt inside loop.
waiting till be interrupted from outs...
multithreading - Java Thread Pool that gets the last task added to the BlockingQueue and discard the others
I want a thread pool with a single thread but with a peculiar behavior for the BlockingQueue:
If I add a job to the queue and then add another job (making the queue hold two jobs), I want the thread to ignore the first job added and get the last one. So, everytime the thread gets a task from the queue, I want it to get the last job added to the queue and discard the others.
Is there any default...
multithreading - Java BlockingQueue messages not processed not processed in full
I am trying to process few million records from a text file (i.e. reading the file sequentially using one thread, and trying to process the retrieved lines using multiple threads). A method call after 'queue.take();' is only executing for the number of times equal to initial capacity allocated to BlockingQueue (100 in this example), and then the process doesn't pickup anymore records.
Could you please help in debug...
multithreading - Finding prime number using BlockingQueue in Java with multi threading
I've implemented a multi thread program using BlockingQueue to test for a number is prime or not.
The requirement is the program will prompt user to input a number and then the program will print every prime number from 2 to inputted number from user in ascending order.
I have 3 class: NumberEnumerationTask for initialize BlockingQueue contains all numbers to be check, PrimeRunner
multithreading - HTTP posts and multiple threads in Java
I am writing an internal Java Applet to do file uploads via HTTP. I started using the built in ClientHttpRequest which worked great if I want to post one after another. When I try to have multiple threads post at the same time, something on the server side freaks out and the connection will hang for large files while still uploading the smaller files. (Large seems to be around 10 megs) After lots of looking, I would no...
multithreading - Tools for finding Shared Mutable data bugs in Java
I have a large legacy system to maintain. The codebase uses threads all over the place and those threads share a lot of mutable data. I know, sounds bad. Anyway, don't answer "rewrite the whole application from scratch" or I'll vote you down :-) I have tried to run some static analysis tools on the codebase, but none of those seem to catch this case which occurs a lot in our source code: multiple threads are reading and wr...
multithreading - synchronizing io operation in java on a string method argument?
This question already has answers here:
multithreading - Stopping a Thread in Java?
This question already has answers here:
multithreading - Threading issues in a Java HashMap
Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause & I was hoping you all could help.
We have a system that looks up latitude & longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat & long of a zip code tend to change less often than we release.
multithreading - Firing a mainline event from a background thread in Java
My question pertains to multi-threading in Java. I'm translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called BackgroundWorker, which allows the coder to perform a task on another thread, a lot like SwingWorker in Java. The only distinct difference ...
multithreading - Java: Run a Callable in a separate process
Given an instance x of Callable<T>, how can I run x in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a Process from a Callable? Is there a standard Executor that gives control over input and output?
[UPDATE] It's not important that the Callable
multithreading - How can you ensure in java that a block of code can not be interrupted by any other thread
exampl:
new Thread(new Runnable() {
public void run() {
while(condition) {
*code that must not be interrupted*
*some more code*
}
}
}).start();
SomeOtherThread.start();
YetAntherThread.start();
How can you ensure that code that must not be interrupted won't be interrupted?
multithreading - Java while loop and Threads!
This question already has answers here:
multithreading - In Java critical sections, what should I synchronize on?
In Java, the idiomatic way to declare critical sections in the code is the following:
private void doSomething() {
// thread-safe code
synchronized(this) {
// thread-unsafe code
}
// thread-safe code
}
Almost all blocks synchronize on this, but is there a particular reason for this? Are there other possibilities? Are there any best practices on what object to sync...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)