private Collection<ClientServerExchangeLockContext> queryLock(LockID lock) {
    final ThreadID current = this.threadManager.getThreadID();

    this.inFlightLockQueries.put(current, lock);
    this.remoteLockManager.query(lock, this.threadManager.getThreadID());

    boolean interrupted = false;
    try {
      while (true) {
        synchronized (lock) {
          final Object data = this.inFlightLockQueries.get(current);
          if (data instanceof Collection) {
            return castToCollection(data);
          } else {
            try {
              lock.wait();
            } catch (final InterruptedException e) {
              interrupted = true;
            }
          }
        }
      }
    } finally {
      Util.selfInterruptIfNeeded(interrupted);
    }
  }
  @Override
  public synchronized T fetchEntity()
      throws EntityNotFoundException, EntityVersionMismatchException {
    EntityClientEndpoint endpoint = null;
    try {
      ClientInstanceID clientInstanceID =
          new ClientInstanceID(this.nextClientInstanceID.getAndIncrement());
      EntityDescriptor entityDescriptor =
          new EntityDescriptor(getEntityID(), clientInstanceID, this.version);
      endpoint =
          this.entityManager.fetchEntity(
              entityDescriptor, entityClientService.getMessageCodec(), null);
    } catch (EntityException e) {
      // In this case, we want to close the endpoint but still throw back the exception.
      // Note that we must externally only present the specific exception types we were expecting.
      // Thus, we need to check
      // that this is one of those supported types, asserting that there was an unexpected wire
      // inconsistency, otherwise.
      if (e instanceof EntityNotFoundException) {
        throw (EntityNotFoundException) e;
      } else if (e instanceof EntityVersionMismatchException) {
        throw (EntityVersionMismatchException) e;
      } else {
        throw Assert.failure("Unsupported exception type returned to fetch", e);
      }
    } catch (final Throwable t) {
      Util.printLogAndRethrowError(t, logger);
    }

    // Note that a failure to resolve the endpoint would have thrown so this can't be null.
    if (endpoint == null) {
      Assert.assertNotNull(endpoint);
    }
    return (T) entityClientService.create(endpoint);
  }
  /** ******************************* */
  private void waitUntilRunning() {
    this.stateGuard.readLock().lock();
    try {
      if (this.state == State.RUNNING) {
        return;
      }
    } finally {
      this.stateGuard.readLock().unlock();
    }

    boolean interrupted = false;
    this.stateGuard.writeLock().lock();
    try {
      while (this.state != State.RUNNING) {
        try {
          if (isShutdown()) {
            throw new TCNotRunningException();
          }
          this.runningCondition.await();
        } catch (final InterruptedException e) {
          interrupted = true;
        }
      }
    } finally {
      this.stateGuard.writeLock().unlock();
      Util.selfInterruptIfNeeded(interrupted);
    }
  }
 @Override
 public synchronized void waitForHandshake() {
   boolean isInterrupted = false;
   try {
     while (this.disconnected && !this.isShutdown()) {
       try {
         wait();
       } catch (InterruptedException e) {
         this.logger.error("Interrupted while waiting for handshake");
         isInterrupted = true;
       }
     }
   } finally {
     Util.selfInterruptIfNeeded(isInterrupted);
   }
 }
 private void blockIfNecessary() {
   boolean isInterrupted = false;
   try {
     while (bytes >= maxSegmentBytes) {
       try {
         sizeFullCondition.await();
       } catch (InterruptedException e) {
         isInterrupted = true;
       }
     }
   } finally {
     if (isInterrupted) {
       Util.selfInterruptIfNeeded(isInterrupted);
     }
   }
 }
    void addSelectorTask(final Runnable task) {
      boolean isInterrupted = false;

      try {
        while (true) {
          try {
            this.selectorTasks.put(task);
            break;
          } catch (InterruptedException e) {
            logger.warn(e);
            isInterrupted = true;
          }
        }
      } finally {
        this.selector.wakeup();
        Util.selfInterruptIfNeeded(isInterrupted);
      }
    }
    private Selector createSelector() {
      Selector selector1 = null;

      final int tries = 3;

      boolean interrupted = false;
      try {
        for (int i = 0; i < tries; i++) {
          try {
            selector1 = Selector.open();
            return selector1;
          } catch (IOException ioe) {
            throw new RuntimeException(ioe);
          } catch (NullPointerException npe) {
            if (i < tries && NIOWorkarounds.selectorOpenRace(npe)) {
              System.err.println(
                  "Attempting to work around sun bug 6427854 (attempt "
                      + (i + 1)
                      + " of "
                      + tries
                      + ")");
              try {
                Thread.sleep(new Random().nextInt(20) + 5);
              } catch (InterruptedException ie) {
                interrupted = true;
              }
              continue;
            }
            throw npe;
          }
        }
      } finally {
        Util.selfInterruptIfNeeded(interrupted);
      }

      return selector1;
    }
    private void selectLoop() throws IOException {
      Assert.eval(Thread.currentThread() == this);

      Selector localSelector = this.selector;
      LinkedBlockingQueue localSelectorTasks = this.selectorTasks;

      while (true) {
        final int numKeys;
        try {
          numKeys = localSelector.select();
        } catch (IOException ioe) {
          if (NIOWorkarounds.linuxSelectWorkaround(ioe)) {
            logger.warn("working around Sun bug 4504001");
            continue;
          }

          if (NIOWorkaroundsTemp.solarisSelectWorkaround(ioe)) {
            logger.warn("working around Solaris select IOException");
            continue;
          }

          throw ioe;
        } catch (CancelledKeyException cke) {
          logger.warn("Cencelled Key " + cke);
          continue;
        }

        if (isStopRequested()) {
          if (logger.isDebugEnabled()) {
            logger.debug("Select loop terminating");
          }
          return;
        }

        boolean isInterrupted = false;
        // run any pending selector tasks
        while (true) {
          Runnable task;
          while (true) {
            try {
              task = (Runnable) localSelectorTasks.poll(0, TimeUnit.MILLISECONDS);
              break;
            } catch (InterruptedException ie) {
              logger.error("Error getting task from task queue", ie);
              isInterrupted = true;
            }
          }

          if (null == task) {
            break;
          }

          try {
            task.run();
          } catch (Exception e) {
            logger.error("error running selector task", e);
          }
        }
        Util.selfInterruptIfNeeded(isInterrupted);

        final Set selectedKeys = localSelector.selectedKeys();
        if ((0 == numKeys) && (0 == selectedKeys.size())) {
          continue;
        }

        for (Iterator iter = selectedKeys.iterator(); iter.hasNext(); ) {
          SelectionKey key = (SelectionKey) iter.next();
          iter.remove();

          if (null == key) {
            logger.error("Selection key is null");
            continue;
          }

          try {

            if (key.isAcceptable()) {
              doAccept(key);
              continue;
            }

            if (key.isConnectable()) {
              doConnect(key);
              continue;
            }

            if (isReader() && key.isValid() && key.isReadable()) {
              int read;
              TCChannelReader reader = (TCChannelReader) key.attachment();
              do {
                read = reader.doRead();
                this.bytesRead.addAndGet(read);
              } while ((read != 0) && key.isReadable());
            }

            if (key.isValid() && !isReader() && key.isWritable()) {
              int written = ((TCChannelWriter) key.attachment()).doWrite();
              this.bytesWritten.addAndGet(written);
            }

            TCConnection conn = (TCConnection) key.attachment();
            if (conn != null && conn.isClosePending()) {
              conn.asynchClose();
            }

          } catch (CancelledKeyException cke) {
            logger.info("selection key cancelled key@" + key.hashCode());
          } catch (Exception e) { // DEV-9369. Do not reconnect on fatal errors.
            logger.info("Unhandled exception occured on connection layer", e);
            TCConnectionImpl conn = (TCConnectionImpl) key.attachment();
            // TCConnectionManager will take care of closing and cleaning up resources
            conn.fireErrorEvent(new RuntimeException(e), null);
          }
        } // for
      } // while (true)
    }