1

I have a private Stack S which is filled with objects from out-side of the class (using methods). A ListenableFuture should read the stack and retrieve an Object from it, but if the stack is empty it should wait for an object to be inserted to the stack and then retrieve it. I'm not sure how to implement this.

My idea was to use Wait / Notify for the ListenableFuture but is this correct logic (working with Guava)? What other options do I have?

Thanks in advance, Guy


ListenableFuture and Guava don't come into this at all. The way to do this is to implement the stack with LinkedBlockingDeque, have the method to add elements to the stack use addFirst, and use pollFirst(long, TimeUnit) to wait the specified amount of time for an object to get inserted.

Never use low-level concurrency tools like wait and notify if you can do the same job with library support.

4

1 回答 1

7

ListenableFuture 和 Guava 根本没有涉及到这一点。这样做的方法是使用 LinkedBlockingDeque 实现堆栈,使用addFirst向堆栈添加元素的方法,并使用 pollFirst(long, TimeUnit) 等待指定的时间量以插入对象。

如果您可以通过库支持完成相同的工作,切勿使用诸如等待和通知之类的低级并发工具。

于 2011-12-26T18:26:05.207 回答