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 {
/**
* 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);
} Well, that's exactly what the bounded new ArrayBlockingQueue(1) is for (use the 'add' method, not 'put'). The object is pretty lightweight in terms of synchronization and the memory overhead shouldn't hurt unless you have tens of thousands of them. Do you have any special concerns?
以上就是Java BlockingQueue of Size=1?的详细内容,更多请关注web前端其它相关文章!