private void handleRefreshException(Exception e) { if (e instanceof AlreadyClosedException) { // ignore } else if (e instanceof RefreshFailedEngineException) { RefreshFailedEngineException rfee = (RefreshFailedEngineException) e; if (rfee.getCause() instanceof InterruptedException) { // ignore, we are being shutdown } else if (rfee.getCause() instanceof ClosedByInterruptException) { // ignore, we are being shutdown } else if (rfee.getCause() instanceof ThreadInterruptedException) { // ignore, we are being shutdown } else { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform engine refresh", e); } } } else { if (state != IndexShardState.CLOSED) { logger.warn("Failed to perform engine refresh", e); } } }
@Override public synchronized void close() { //System.out.println("NRT: set finish"); finish = true; // So thread wakes up and notices it should finish: reopenLock.lock(); try { reopenCond.signal(); } finally { reopenLock.unlock(); } try { join(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } // Max it out so any waiting search threads will return: searchingGen = Long.MAX_VALUE; notifyAll(); }
/** * Blocks if documents writing is currently in a stalled state. * */ void waitIfStalled() { if (stalled) { synchronized (this) { if (stalled) { // react on the first wakeup call! // don't loop here, higher level logic will re-stall! try { incWaiters(); wait(); decrWaiters(); } catch (InterruptedException e) { throw new ThreadInterruptedException(e); } } } } }
/** Attempts to obtain an exclusive lock within amount of * time given. Polls once per {@link #LOCK_POLL_INTERVAL} * (currently 1000) milliseconds until lockWaitTimeout is * passed. * @param lockWaitTimeout length of time to wait in * milliseconds or {@link * #LOCK_OBTAIN_WAIT_FOREVER} to retry forever * @return true if lock was obtained * @throws LockObtainFailedException if lock wait times out * @throws IllegalArgumentException if lockWaitTimeout is * out of bounds * @throws IOException if obtain() throws IOException */ public final boolean obtain(long lockWaitTimeout) throws IOException { failureReason = null; boolean locked = obtain(); if (lockWaitTimeout < 0 && lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER) throw new IllegalArgumentException("lockWaitTimeout should be LOCK_OBTAIN_WAIT_FOREVER or a non-negative number (got " + lockWaitTimeout + ")"); long maxSleepCount = lockWaitTimeout / LOCK_POLL_INTERVAL; long sleepCount = 0; while (!locked) { if (lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER && sleepCount++ >= maxSleepCount) { String reason = "Lock obtain timed out: " + this.toString(); if (failureReason != null) { reason += ": " + failureReason; } throw new LockObtainFailedException(reason, failureReason); } try { Thread.sleep(LOCK_POLL_INTERVAL); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } locked = obtain(); } return locked; }
/** * Stop the update thread. If the update thread is not running, silently does * nothing. This method returns after the update thread has stopped. */ public synchronized void stopUpdateThread() { if (updateThread != null) { // this will trigger the thread to terminate if it awaits the lock. // otherwise, if it's in the middle of replication, we wait for it to // stop. updateThread.stop.countDown(); try { updateThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ThreadInterruptedException(e); } updateThread = null; } }
public void testOverflowInt() throws Exception { Thread t = new Thread() { @Override public void run() { try { new SimpleRateLimiter(1).pause((long) (1.5*Integer.MAX_VALUE*1024*1024/1000)); fail("should have been interrupted"); } catch (ThreadInterruptedException tie) { // expected } } }; t.start(); Thread.sleep(10); t.interrupt(); }
/** * Waits for the target generation to become visible in * the searcher. If the current searcher is older than * the target generation, this method will block until the * searcher has been reopened by another thread via * {@link #maybeRefresh}, the given waiting time has elapsed, or until * the NRTManager is closed. * <p> * NOTE: if the waiting time elapses before the requested target generation is * available the current {@link SearcherManager} is returned instead. * * @param targetGen * the generation to wait for * @param time * the time to wait for the target generation * @param unit * the waiting time's time unit */ public void waitForGeneration(long targetGen, long time, TimeUnit unit) { try { final long curGen = writer.getGeneration(); if (targetGen > curGen) { throw new IllegalArgumentException("targetGen=" + targetGen + " was never returned by this NRTManager instance (current gen=" + curGen + ")"); } genLock.lockInterruptibly(); try { if (targetGen > searchingGen) { for (WaitingListener listener : waitingListeners) { listener.waiting(targetGen); } while (targetGen > searchingGen) { if (!waitOnGenCondition(time, unit)) { return; } } } } finally { genLock.unlock(); } } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } }
@Override public void rollback() throws IOException { Directory dir = getDirectory(); try { while (true) { try { super.rollback(); } catch (ThreadInterruptedException e) { // don't allow interruption continue; } break; } } finally { isClosed = true; directoryFactory.release(dir); numCloses.incrementAndGet(); } }
@Override public void run() { while (!stop) { // TODO: Use System.nanoTime() when Lucene moves to Java SE 5. counter.addAndGet(resolution); try { Thread.sleep( resolution ); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } }
public synchronized void waitForFlush() { while (flushingWriters.size() != 0) { try { this.wait(); } catch (InterruptedException e) { throw new ThreadInterruptedException(e); } } }
/** Called when an exception is hit in a background merge * thread */ protected void handleMergeException(Throwable exc) { try { // When an exception is hit during merge, IndexWriter // removes any partial files and then allows another // merge to run. If whatever caused the error is not // transient then the exception will keep happening, // so, we sleep here to avoid saturating CPU in such // cases: Thread.sleep(250); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } throw new MergePolicy.MergeException(exc, dir); }
private synchronized void doWait() { // NOTE: the callers of this method should in theory // be able to do simply wait(), but, as a defense // against thread timing hazards where notifyAll() // fails to be called, we wait for at most 1 second // and then return so caller can check if wait // conditions are satisfied: try { wait(1000); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } }
/** * run the Interruptable, capturing the executing thread. Concurrent calls to {@link #cancel(String)} will interrupt this thread * causing the call to prematurely return. * * @param interruptable code to run */ public void execute(Interruptable interruptable) { boolean wasInterrupted = add(); RuntimeException throwable = null; try { interruptable.run(); } catch (InterruptedException | ThreadInterruptedException e) { // assume this is us and ignore } catch (RuntimeException t) { throwable = t; } finally { remove(); } // we are now out of threads collection so we can't be interrupted any more by this class // restore old flag and see if we need to fail if (wasInterrupted) { Thread.currentThread().interrupt(); } else { // clear the flag interrupted flag as we are checking for failure.. Thread.interrupted(); } synchronized (this) { if (isCancelled()) { onCancel(reason, throwable); } else if (throwable != null) { // if we're not canceling, we throw the original exception throw throwable; } } }
protected void fsync(String name) throws IOException { File fullFile = new File(directory, name); boolean success = false; int retryCount = 0; IOException exc = null; while (!success && retryCount < 5) { retryCount++; RandomAccessFile file = null; try { try { file = new RandomAccessFile(fullFile, "rw"); file.getFD().sync(); success = true; } finally { if (file != null) file.close(); } } catch (IOException ioe) { if (exc == null) exc = ioe; try { // Pause 5 msec Thread.sleep(5); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } } if (!success) // Throw original exception throw exc; }
/** Pauses, if necessary, to keep the instantaneous IO * rate at or below the target. NOTE: multiple threads * may safely use this, however the implementation is * not perfectly thread safe but likely in practice this * is harmless (just means in some rare cases the rate * might exceed the target). It's best to call this * with a biggish count, not one byte at a time. * @return the pause time in nano seconds * */ @Override public long pause(long bytes) { if (bytes == 1) { return 0; } // TODO: this is purely instantaneous rate; maybe we // should also offer decayed recent history one? final long targetNS = lastNS = lastNS + ((long) (bytes * nsPerByte)); long curNS = System.nanoTime(); if (lastNS < curNS) { lastNS = curNS; } // While loop because Thread.sleep doesn't always sleep // enough: while(true) { final long pauseNS = targetNS - curNS; if (pauseNS > 0) { try { Thread.sleep((int) (pauseNS/1000000), (int) (pauseNS % 1000000)); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } curNS = System.nanoTime(); continue; } break; } return targetNS; }
/** Attempts to obtain an exclusive lock within amount of * time given. Polls once per {@link #LOCK_POLL_INTERVAL} * (currently 1000) milliseconds until lockWaitTimeout is * passed. * @param lockWaitTimeout length of time to wait in * milliseconds or {@link * #LOCK_OBTAIN_WAIT_FOREVER} to retry forever * @return true if lock was obtained * @throws LockObtainFailedException if lock wait times out * @throws IllegalArgumentException if lockWaitTimeout is * out of bounds * @throws IOException if obtain() throws IOException */ public boolean obtain(long lockWaitTimeout) throws IOException { failureReason = null; boolean locked = obtain(); if (lockWaitTimeout < 0 && lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER) throw new IllegalArgumentException("lockWaitTimeout should be LOCK_OBTAIN_WAIT_FOREVER or a non-negative number (got " + lockWaitTimeout + ")"); long maxSleepCount = lockWaitTimeout / LOCK_POLL_INTERVAL; long sleepCount = 0; while (!locked) { if (lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER && sleepCount++ >= maxSleepCount) { String reason = "Lock obtain timed out: " + this.toString(); if (failureReason != null) { reason += ": " + failureReason; } LockObtainFailedException e = new LockObtainFailedException(reason); if (failureReason != null) { e.initCause(failureReason); } throw e; } try { Thread.sleep(LOCK_POLL_INTERVAL); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } locked = obtain(); } return locked; }
private synchronized void setXid(Xid xid) throws XAException { // start method should have been called with TMJOIN // because isSameRM would have returned true if(currentXid != null && currentXid.equals(xid)) { throw new XAException(XAException.XAER_DUPID); } while(state != TransactionState.NONE && currentXid != null) { logger.finest("Blocking thread with transaction (id=" + xid + " ) because current transaction (id=" + currentXid + ") is still in progress"); try { wait(); } catch (InterruptedException e) { if(Thread.interrupted()) { // clears interrupted status logger.log(Level.WARNING, "Thread waiting for transaction (id=" + currentXid + ") to complete has been interrupted?", e); throw new ThreadInterruptedException(e); } } } currentXid = xid; state = TransactionState.ACTIVE; }
@Override public void run () { while (!stop) { counter.addAndGet(resolution); try { Thread.sleep(resolution); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); }; }; }
String[] next() throws NoMoreDataException { if (t == null) { threadDone = false; t = new Thread(this); t.setDaemon(true); t.start(); } String[] result; synchronized(this){ while(tuple == null && nmde == null && !threadDone && !stopped) { try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } if (tuple != null) { result = tuple; tuple = null; notify(); return result; } if (nmde != null) { // Set to null so we will re-start thread in case // we are re-used: t = null; throw nmde; } // The thread has exited yet did not hit end of // data, so this means it hit an exception. We // throw NoMorDataException here to force // benchmark to stop the current alg: throw new NoMoreDataException(); } }
@SuppressWarnings("synthetic-access") @Override public void run() { while (true) { long time = System.currentTimeMillis(); updateLock.lock(); try { doUpdate(); } catch (Throwable t) { handleUpdateException(t); } finally { updateLock.unlock(); } time = System.currentTimeMillis() - time; // adjust timeout to compensate the time spent doing the replication. final long timeout = interval - time; if (timeout > 0) { try { // this will return immediately if we were ordered to stop (count=0) // or the timeout has elapsed. if it returns true, it means count=0, // so terminate. if (stop.await(timeout, TimeUnit.MILLISECONDS)) { return; } } catch (InterruptedException e) { // if we were interruted, somebody wants to terminate us, so just // throw the exception further. Thread.currentThread().interrupt(); throw new ThreadInterruptedException(e); } } } }
void doSleep(Random random, int length) { int sTime = length<10 ? sleepMillis : (int) (sleepMillis * Math.log(length)); if (random!=null) { sTime = random.nextInt(sTime); } try { Thread.sleep(sTime); } catch (InterruptedException e) { throw new ThreadInterruptedException(e); } }
@Override public void close() throws IOException { try { Thread.sleep(50); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } finally { super.close(); } }
public SlowOpeningMockIndexInputWrapper(MockDirectoryWrapper dir, String name, IndexInput delegate) throws IOException { super(dir, name, delegate); try { Thread.sleep(50); } catch (InterruptedException ie) { try { super.close(); } catch (Throwable ignore) {} // we didnt open successfully throw new ThreadInterruptedException(ie); } }