Drains the queue as plain #drain(BlockingQueue, Collection, int, long, TimeUnit), but with a different behavior in case it is interrupted while waiting. In that case, the operation will continue as usual, and in the end the thread's interruption status will be set (no {@code InterruptedExcept
(
BlockingQueue<E> q,
Collection<? super E> buffer,
int numElements,
long timeout,
TimeUnit unit)
| 338 | */ |
| 339 | |
| 340 | @Beta |
| 341 | @CanIgnoreReturnValue |
| 342 | public static <E> int drainUninterruptibly( |
| 343 | BlockingQueue<E> q, |
| 344 | Collection<? super E> buffer, |
| 345 | int numElements, |
| 346 | long timeout, |
| 347 | TimeUnit unit) { |
| 348 | Preconditions.checkNotNull(buffer); |
| 349 | long deadline = System.nanoTime() + unit.toNanos(timeout); |
| 350 | int added = 0; |
| 351 | boolean interrupted = false; |
| 352 | try { |
| 353 | while (added < numElements) { |
| 354 | // we could rely solely on #poll, but #drainTo might be more efficient when there are |
| 355 | // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) |
| 356 | added += q.drainTo(buffer, numElements - added); |
| 357 | if (added < numElements) { // not enough elements immediately available; will have to poll |
| 358 | E e; // written exactly once, by a successful (uninterrupted) invocation of #poll |
| 359 | while (true) { |
| 360 | try { |
| 361 | e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); |
| 362 | break; |
| 363 | } catch (InterruptedException ex) { |
| 364 | interrupted = true; // note interruption and retry |
| 365 | } |
| 366 | } |
| 367 | if (e == null) { |
| 368 | break; // we already waited enough, and there are no more elements in sight |
| 369 | } |
| 370 | buffer.add(e); |
| 371 | added++; |
| 372 | } |
| 373 | } |
| 374 | } finally { |
| 375 | if (interrupted) { |
| 376 | Thread.currentThread().interrupt(); |
| 377 | } |
| 378 | } |
| 379 | return added; |
| 380 | } |
| 381 | |
| 382 | /** |
| 383 | * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to |
nothing calls this directly
no test coverage detected