Завершение вызова на BlockingQueue#peek()
в Callable
, выполнение и ожидание на Future<T>.get(long, TimeUnit)
:
final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
ExecutorService executor = Executors.newCachedThreadPool();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
scheduler.schedule(new Runnable()
{
@Override
public void run()
{
String e = UUID.randomUUID().toString();
System.out.println("adding = " + e);
queue.add(e);
}
}, 2, TimeUnit.SECONDS);
Callable<String> task = new Callable<String>()
{
@Override
public String call() throws Exception
{
String result = null;
while ((result = queue.peek()) == null)
{
Thread.sleep(100L);
}
return result;
}
};
String peeked = null;
try
{
peeked = executor.submit(task).get(1, TimeUnit.SECONDS);
System.out.println("this should never be printed");
queue.poll();
}
catch (TimeoutException e)
{
System.out.println("null: peeked = " + peeked);
e.printStackTrace();
}
try
{
peeked = executor.submit(task).get(2, TimeUnit.SECONDS);
System.out.println("not null: peeked = " + peeked);
}
catch (TimeoutException e)
{
e.printStackTrace();
System.out.println("should not throw an exception");
}