示例#1
0
  private boolean pauseForInput() throws InterruptedException {
    long silentTime;
    boolean paused = false;
    synchronized (userPackets) {
      silentTime = System.currentTimeMillis();

      // Wait with the audio on
      while (shouldRun
          && userPackets.isEmpty()
          && (silentTime + standbyTreshold) > System.currentTimeMillis()) {

        userPackets.wait((silentTime + standbyTreshold) - System.currentTimeMillis() + 1);
      }

      // If conditions are still not filled, pause audio and wait more.
      if (shouldRun && userPackets.isEmpty()) {
        at.pause();
        paused = true;
        Log.i(Globals.LOG_TAG, "AudioOutput: Standby timeout reached. Audio paused.");

        while (shouldRun && userPackets.isEmpty()) {
          userPackets.wait();
        }
      }
    }
    return paused;
  }
 public CreateCoordinationContextDetails getCreateCoordinationContextDetails(
     final String messageId, long timeout) {
   final long endTime = System.currentTimeMillis() + timeout;
   synchronized (messageIdMap) {
     long now = System.currentTimeMillis();
     while (now < endTime) {
       final CreateCoordinationContextDetails details =
           (CreateCoordinationContextDetails) messageIdMap.remove(messageId);
       if (details != null) {
         return details;
       }
       try {
         messageIdMap.wait(endTime - now);
       } catch (final InterruptedException ie) {
       } // ignore
       now = System.currentTimeMillis();
     }
     final CreateCoordinationContextDetails details =
         (CreateCoordinationContextDetails) messageIdMap.remove(messageId);
     if (details != null) {
       return details;
     }
   }
   throw new NullPointerException("Timeout occurred waiting for id: " + messageId);
 }
示例#3
0
  /**
   * Wait for a response to a particular message.
   *
   * @see IMessenger#exchangeMessage(ProbeMessage)
   * @param sequenceNumber The sequence number of the message to wait for a response to.
   * @return The response message.
   * @throws Exception on fatal errors
   */
  IProbeMessage readResponse(int sequenceNumber) throws MessengerException {
    long start = System.currentTimeMillis();

    synchronized (responseMap) {
      while (responseMap.containsKey(sequenceNumber) == false) {

        long elapsed = System.currentTimeMillis() - start;

        if (elapsed >= readTimeout) {
          markAbandoned(sequenceNumber);
          throw new MessengerException("Timeout reading response message");
        }

        if (isAlive() == false) {
          /* probably redundant */
          markAbandoned(sequenceNumber);
          throw new MessengerClosedException();
        }

        try {
          responseMap.wait(readTimeout - elapsed);
        } catch (InterruptedException e) {
          markAbandoned(sequenceNumber);
          Thread.currentThread().interrupt();
          // XXX should be chained?
          throw new MessengerException("Interrupted while reading response");
        }
      }

      return responseMap.remove(sequenceNumber);
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.wst.jsdt.debug.transport.TransportService#accept(org.eclipse.wst.jsdt.debug.transport.ListenerKey, long, long)
   */
  public Connection accept(ListenerKey key, long attachTimeout, long handshakeTimeout)
      throws IOException {
    long timeout = attachTimeout;
    if (timeout > 0) {
      if (timeout > Integer.MAX_VALUE) {
        timeout = Integer.MAX_VALUE; // approximately 25 days!
      }
    }

    synchronized (listeners) {
      if (!listeners.containsKey(key))
        throw new IllegalStateException("not listening"); // $NON-NLS-1$

      if (listeners.get(key) != null)
        throw new IllegalStateException(
            "PipedTransport only accepts one accept at a time"); //$NON-NLS-1$

      PipedInputStream serveris = new PipedInputStream();
      PipedOutputStream clientos = new PipedOutputStream();
      PipedOutputStream serveros = new PipedOutputStream();
      PipedInputStream clientis = new PipedInputStream();
      serveris.connect(clientos);
      serveros.connect(clientis);

      PipedConnection clientConnection = new PipedConnection(clientis, clientos);
      PipedConnection serverConnection = new PipedConnection(serveris, serveros);

      listeners.put(key, clientConnection);
      listeners.notifyAll();
      long startTime = System.currentTimeMillis();
      while (true) {
        try {
          listeners.wait(timeout);
        } catch (InterruptedException e) {
          clientConnection.close(); // Close unused client connection (and its streams);
          serverConnection.close(); // Close unused server connection (and its streams);
          throw new IOException("accept failed: interrupted"); // $NON-NLS-1$
        }
        if (!listeners.containsKey(key)) {
          clientConnection.close(); // Close unused client connection (and its streams);
          serverConnection.close(); // Close unused server connection (and its streams);
          throw new IOException("accept failed: stopped listening"); // $NON-NLS-1$
        }

        if (listeners.get(key) != null) {
          if (System.currentTimeMillis() - startTime > timeout) {
            listeners.put(key, null);
            clientConnection.close(); // Close unused client connection (and its streams);
            serverConnection.close(); // Close unused server connection (and its streams);
            throw new IOException("accept failed: timed out"); // $NON-NLS-1$
          }
          continue;
        }
        return serverConnection; // From this point both, the server and the client,
        // are responsible to close their connections
      }
    }
  }
  /**
   * Waits until all rete update operations are settled in all containers. Returns immediately, if
   * no updates are pending.
   *
   * <p>To be called from any user thread.
   */
  public void waitForReteTermination() {
    if (threads > 0) {
      synchronized (globalTerminationCriteria) {
        while (!globalTerminationCriteria.isEmpty()) {
          try {
            globalTerminationCriteria.wait();
          } catch (InterruptedException e) {

          }
        }
      }
    } else headContainer.messageConsumptionSingleThreaded();
  }
示例#6
0
  void lockParticipant(final Participant p, final CoordinationImpl c) {
    synchronized (participants) {
      // wait for participant to be released
      long cutOff = System.currentTimeMillis() + participationTimeOut;
      long waitTime =
          (participationTimeOut > 500) ? participationTimeOut / 500 : participationTimeOut;
      CoordinationImpl current = participants.get(p);
      while (current != null && current != c) {
        if (current.getThread() == c.getThread()) {
          throw new CoordinationException(
              "Participant "
                  + p
                  + " already participating in Coordination "
                  + current.getId()
                  + "/"
                  + current.getName()
                  + " in this thread",
              c,
              CoordinationException.DEADLOCK_DETECTED);
        }

        try {
          participants.wait(waitTime);
        } catch (InterruptedException ie) {
          throw new CoordinationException(
              "Interrupted waiting to add Participant "
                  + p
                  + " currently participating in Coordination "
                  + current.getId()
                  + "/"
                  + current.getName()
                  + " in this thread",
              c,
              CoordinationException.LOCK_INTERRUPTED);
        }

        // timeout waiting for participation
        if (System.currentTimeMillis() > cutOff) {
          throw new CoordinationException(
              "Timed out waiting to join coordinaton", c, CoordinationException.UNKNOWN);
        }

        // check again
        current = participants.get(p);
      }

      // lock participant into coordination
      participants.put(p, c);
    }
  }
  @Nullable
  ProtocolFrame waitForResponse(final int sequence) {
    ProtocolFrame response;
    long until = System.currentTimeMillis() + RESPONSE_TIMEOUT;

    synchronized (myResponseQueue) {
      do {
        try {
          myResponseQueue.wait(1000);
        } catch (InterruptedException ignore) {
        }
        response = myResponseQueue.get(sequence);
      } while (response == null && isConnected() && System.currentTimeMillis() < until);
      myResponseQueue.remove(sequence);
    }

    return response;
  }
示例#8
0
  public void xxWaitForConn() throws Exception {
    log.info(tid() + " XX_WAIT_FOR_CONN (" + id + ")");

    boolean contained = connections.containsKey(id);
    while (contained == false) {
      checkTestMarkedForExit();

      log.info(tid() + " Sleeping for 100 msecs");

      synchronized (connections) {
        try {
          connections.wait(100);
        } catch (InterruptedException ignore) {
        }
      }
      contained = connections.containsKey(id);
    }
    log.info(tid() + " Got it");
  }
示例#9
0
  public void xxWaitForTx() throws Exception {
    log.info(tid() + " XX_WAIT_FOR_TX (" + id + ")");

    Transaction tx = (Transaction) transactions.get(id);
    while (tx == null) {
      checkTestMarkedForExit();

      log.info(tid() + " Sleeping for 100 msecs");

      synchronized (transactions) {
        try {
          transactions.wait(100);
        } catch (InterruptedException ignore) {
        }
      }
      tx = (Transaction) transactions.get(id);
    }
    log.info(tid() + " Got it");
  }
示例#10
0
  /**
   * Accrues a lock for the given key. If this thread acquires a lock with key1, any subsequent
   * threads trying to acquire the lock with key2 will block if key1.equals(key2). If
   * key1.equals(key2) is not true, the subsequent thread will acquire the lock for key2 and
   * continue execution.
   *
   * @param key The key
   */
  public final void lock(final Object key) {
    boolean isInterrupted = false;

    try {
      synchronized (keys) {
        while (!acquireLock(key, Thread.currentThread())) {
          keys.wait();
        }
      }

    } catch (InterruptedException e) {
      // Ignore the interruption until we've finished
      isInterrupted = Thread.interrupted();
    }

    if (isInterrupted) {
      // re-interrupt thread if an interruption occured
      Thread.currentThread().interrupt();
    }
  }
 /* (non-Javadoc)
  * @see org.eclipse.wst.jsdt.debug.transport.TransportService#attach(java.lang.String, long, long)
  */
 public Connection attach(String address, long attachTimeout, long handshakeTimeout)
     throws IOException {
   ListenerKey key = new PipedListenerKey(address == null ? Constants.EMPTY_STRING : address);
   Connection connection;
   long startTime = System.currentTimeMillis();
   synchronized (listeners) {
     connection = (Connection) listeners.get(key);
     while (connection == null) {
       if (System.currentTimeMillis() - startTime > attachTimeout)
         throw new IOException("attach failed: timed out"); // $NON-NLS-1$
       try {
         listeners.wait(attachTimeout);
       } catch (InterruptedException e) {
         throw new IOException("attach failed: interrupted"); // $NON-NLS-1$
       }
       connection = (Connection) listeners.get(key);
     }
     listeners.put(key, null);
     listeners.notifyAll();
   }
   return connection;
 }
示例#12
0
 /**
  * Lock given bundle for update. After this only {@link #update(String, String)} and {@link
  * #endUpdate(DPUTemplateRecord, boolean)} can be called.
  *
  * @param directory
  */
 private void lockUpdate(String directory) {
   // wait till the required directory is not in directory
   while (true) {
     synchronized (updatingBundles) {
       if (updatingBundles.containsKey(directory)) {
         // already contains .. check thread
         if (updatingBundles.get(directory) == Thread.currentThread()) {
           // we are owners of the lock, we shall pass
           return;
         }
       } else {
         // not present, add -> lock
         updatingBundles.put(directory, Thread.currentThread());
         return;
       }
       // wait .. this will release lock from synchronised block
       try {
         updatingBundles.wait();
       } catch (InterruptedException e) {
       }
     }
   }
 }
示例#13
0
  @SuppressWarnings("resource")
  protected void openFile() throws IOException {
    synchronized (locked) {
      while (locked.containsKey(filename) && locked.get(filename)) {
        try {
          locked.wait();
        } catch (InterruptedException e) {
        }
      }
      locked.put(filename, true);

      File file = new File(this.filename);
      if (!file.exists()) {
        locked.put(filename, false);
        locked.notifyAll();
        throw new IllegalStateException(
            "Warning: File doesn't exist (anymore):'" + this.filename + "'");
      }

      channel = new RandomAccessFile(file, "rw").getChannel();
      try {
        // TODO: add support for shared locks, allowing parallel reading
        // operations.
        lock = channel.lock();

      } catch (Exception e) {
        channel.close();
        channel = null;
        lock = null;
        locked.put(filename, false);
        locked.notifyAll();
        throw new IllegalStateException("error, couldn't obtain file lock on:" + filename, e);
      }
      fis = new BufferedInputStream(Channels.newInputStream(channel));
      fos = new BufferedOutputStream(Channels.newOutputStream(channel));
    }
  }