Exemplo n.º 1
0
    final void test() throws Exception {
      Future[] futures = new Future[nthreads];
      for (int i = 0; i < nthreads; ++i) futures[i] = pool.submit(this);

      barrier.await();
      Thread.sleep(TIMEOUT);
      boolean tooLate = false;
      for (int i = 1; i < nthreads; ++i) {
        if (!futures[i].cancel(true)) tooLate = true;
        // Unbunch some of the cancels
        if ((i & 3) == 0) Thread.sleep(1 + rng.next() % 10);
      }

      Object f0 = futures[0].get();
      if (!tooLate) {
        for (int i = 1; i < nthreads; ++i) {
          if (!futures[i].isDone() || !futures[i].isCancelled())
            throw new Error("Only one thread should complete");
        }
      } else System.out.print("(cancelled too late) ");

      long endTime = System.nanoTime();
      long time = endTime - timer.startTime;
      if (print) {
        double secs = (double) (time) / 1000000000.0;
        System.out.println("\t " + secs + "s run time");
      }
    }
 private void initialize(Namespace namespace, long instanceOid) {
   this.namespace = namespace;
   this.instanceOid = instanceOid;
   updater = new Updater();
   Thread updaterThread = new Thread(updater);
   updaterThread.start();
 }
Exemplo n.º 3
0
 /** Initializes a random variable */
 private void createRandom() {
   this.random =
       new Random(
           System.currentTimeMillis()
               + Thread.currentThread().getId()
               - Thread.currentThread().hashCode()
               + this.cname.hashCode());
 }
Exemplo n.º 4
0
 /**
  * Adds the specified element to this queue, waiting if necessary for another thread to receive
  * it.
  *
  * @throws InterruptedException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  */
 public void put(E o) throws InterruptedException {
   if (o == null) throw new NullPointerException();
   if (transferer.transfer(o, false, 0) == null) {
     Thread.interrupted();
     throw new InterruptedException();
   }
 }
  public HostConnectionPool(Host host, HostDistance hostDistance, Session.Manager manager)
      throws ConnectionException {
    assert hostDistance != HostDistance.IGNORED;
    this.host = host;
    this.hostDistance = hostDistance;
    this.manager = manager;

    this.newConnectionTask =
        new Runnable() {
          @Override
          public void run() {
            addConnectionIfUnderMaximum();
            scheduledForCreation.decrementAndGet();
          }
        };

    // Create initial core connections
    List<Connection> l =
        new ArrayList<Connection>(options().getCoreConnectionsPerHost(hostDistance));
    try {
      for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
        l.add(manager.connectionFactory().open(host));
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      // If asked to interrupt, we can skip opening core connections, the pool will still work.
      // But we ignore otherwise cause I'm not sure we can do much better currently.
    }
    this.connections = new CopyOnWriteArrayList<Connection>(l);
    this.open = new AtomicInteger(connections.size());

    logger.trace("Created connection pool to host {}", host);
  }
Exemplo n.º 6
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue.
  *
  * @return the head of this queue
  * @throws InterruptedException {@inheritDoc}
  */
 public E take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) available.await();
       else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
 public void shutdown() {
   try {
     shutdown(0, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
   }
 }
Exemplo n.º 8
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         if (nanos <= 0) return null;
         if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos);
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             long timeLeft = available.awaitNanos(delay);
             nanos -= delay - timeLeft;
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
Exemplo n.º 9
0
 // Acquire the lock if state is zero
 public boolean tryAcquire(int acquires) {
   assert acquires == 1; // Otherwise unused
   if (compareAndSetState(0, 1)) {
     setExclusiveOwnerThread(Thread.currentThread());
     return true;
   }
   return false;
 }
Exemplo n.º 10
0
 /**
  * Spins/blocks until node s is matched by a fulfill operation.
  *
  * @param s the waiting node
  * @param timed true if timed wait
  * @param nanos timeout value
  * @return matched node, or s if cancelled
  */
 SNode awaitFulfill(SNode s, boolean timed, long nanos) {
   /*
    * When a node/thread is about to block, it sets its waiter
    * field and then rechecks state at least one more time
    * before actually parking, thus covering race vs
    * fulfiller noticing that waiter is non-null so should be
    * woken.
    *
    * When invoked by nodes that appear at the point of call
    * to be at the head of the stack, calls to park are
    * preceded by spins to avoid blocking when producers and
    * consumers are arriving very close in time.  This can
    * happen enough to bother only on multiprocessors.
    *
    * The order of checks for returning out of main loop
    * reflects fact that interrupts have precedence over
    * normal returns, which have precedence over
    * timeouts. (So, on timeout, one last check for match is
    * done before giving up.) Except that calls from untimed
    * SynchronousQueue.{poll/offer} don't check interrupts
    * and don't wait at all, so are trapped in transfer
    * method rather than calling awaitFulfill.
    */
   long lastTime = timed ? System.nanoTime() : 0;
   Thread w = Thread.currentThread();
   SNode h = head;
   int spins = (shouldSpin(s) ? (timed ? maxTimedSpins : maxUntimedSpins) : 0);
   for (; ; ) {
     if (w.isInterrupted()) s.tryCancel();
     SNode m = s.match;
     if (m != null) return m;
     if (timed) {
       long now = System.nanoTime();
       nanos -= now - lastTime;
       lastTime = now;
       if (nanos <= 0) {
         s.tryCancel();
         continue;
       }
     }
     if (spins > 0) spins = shouldSpin(s) ? (spins - 1) : 0;
     else if (s.waiter == null) s.waiter = w; // establish waiter so can park next iter
     else if (!timed) LockSupport.park(this);
     else if (nanos > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanos);
   }
 }
Exemplo n.º 11
0
  /**
   * End the RTP Session. This will halt all threads and send bye-messages to other participants.
   *
   * <p>RTCP related threads may require several seconds to wake up and terminate.
   */
  public void endSession() {
    this.endSession = true;

    // No more RTP packets, please
    if (this.mcSession) {
      this.rtpMCSock.close();
    } else {
      this.rtpSock.close();
    }

    // Signal the thread that pushes data to application
    this.pktBufLock.lock();
    try {
      this.pktBufDataReady.signalAll();
    } finally {
      this.pktBufLock.unlock();
    }
    // Interrupt what may be sleeping
    this.rtcpSession.senderThrd.interrupt();

    // Give things a chance to cool down.
    try {
      Thread.sleep(50);
    } catch (Exception e) {
    }
    ;

    this.appCallerThrd.interrupt();

    // Give things a chance to cool down.
    try {
      Thread.sleep(50);
    } catch (Exception e) {
    }
    ;

    if (this.rtcpSession != null) {
      // No more RTP packets, please
      if (this.mcSession) {
        this.rtcpSession.rtcpMCSock.close();
      } else {
        this.rtcpSession.rtcpSock.close();
      }
    }
  }
Exemplo n.º 12
0
 private static void joinUninterruptibly(Thread jt) {
   do {
     try {
       jt.join();
       break;
     } catch (InterruptedException ie) {
     }
   } while (true);
 }
Exemplo n.º 13
0
        @Override
        public void run() {
          reentrantLock.lock();
          // if pool-1-thread-1 is the last, no thread will notify it;
          while (Thread.currentThread().getName().equals("pool-1-thread-1")) {
            try {
              condition.await();

            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          for (Integer integer : list) {
            System.out.println(integer);
            System.out.println(Thread.currentThread().getName());
          }
          condition.signalAll();
          reentrantLock.unlock();
        }
Exemplo n.º 14
0
  private static void runExecutionBoundedTest(int nthreads, List<Counter> counters, int nexecutions)
      throws InterruptedException {
    final List<CounterThread> threads = new ArrayList<CounterThread>();
    for (int i = 0; i < nthreads; i++) {
      CounterThread t;
      t = new CounterThread(counters.get(i % counters.size()), nexecutions);
      t.start();
      threads.add(t);
    }

    CounterThread.shoot(); // let all the threads go crazy at the same time

    for (int i = 0; i < nthreads; i++) {
      CounterThread t = threads.get(i);
      t.join(30000);
      if (t.isAlive()) {
        System.out.println("stuck thread name: " + t.toString());
        System.out.println("stuck thread state: " + t.getState());
        safe.ReentrantLock l = (safe.ReentrantLock) t.getLock();
        System.out.println("thread waiting lock: " + l);
        System.out.println("stuck thread increments: " + t.getExecutions());
        System.out.println("stuck thread counter value: " + t.getCounterCount());
        Thread other = l.getOwner();
        System.out.println("lock owner: " + other);
        if (other != null) {
          System.out.println("owner name: " + other.toString());
          System.out.println("state owner: " + other.getState());
        }
        // Keep program alive to dump thread stacks with: jstack -l $(pidof java)
        System.out.println(
            java.lang.management.ManagementFactory.getThreadMXBean().getPeakThreadCount());
        while (true) {}
      }
    }
    long sum = 0;
    for (int i = 0; i < counters.size(); ++i) {
      sum += counters.get(i).getCount();
    }
    System.out.println(sum);
    System.out.println(
        java.lang.management.ManagementFactory.getThreadMXBean().getPeakThreadCount());
  }
Exemplo n.º 15
0
  /**
   * @param key Removed key.
   * @param ver Removed version.
   * @throws IgniteCheckedException If failed.
   */
  public void onDeferredDelete(KeyCacheObject key, GridCacheVersion ver)
      throws IgniteCheckedException {
    try {
      T2<KeyCacheObject, GridCacheVersion> evicted = rmvQueue.add(new T2<>(key, ver));

      if (evicted != null) cctx.dht().removeVersionedEntry(evicted.get1(), evicted.get2());
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();

      throw new IgniteInterruptedCheckedException(e);
    }
  }
Exemplo n.º 16
0
 @Override
 // Keep adding an amount to the account
 public void run() {
   try { // Purposely delay it to let the withdraw method proceed
     while (true) {
       account.deposit((int) (Math.random() * 10) + 1);
       Thread.sleep(1000);
     }
   } catch (InterruptedException ex) {
     ex.printStackTrace();
   }
 }
Exemplo n.º 17
0
  public static void main(String[] argv) throws Exception {
    mbean = newPlatformMXBeanProxy(server, THREAD_MXBEAN_NAME, ThreadMXBean.class);

    if (!mbean.isSynchronizerUsageSupported()) {
      System.out.println("Monitoring of synchronizer usage not supported");
      return;
    }

    thread.setDaemon(true);
    thread.start();

    // wait until myThread acquires mutex and lock owner is set.
    while (!(mutex.isLocked() && mutex.getLockOwner() == thread)) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    long[] ids = new long[] {thread.getId()};

    // validate the local access
    ThreadInfo[] infos = getThreadMXBean().getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    // validate the remote access
    infos = mbean.getThreadInfo(ids, true, true);
    if (infos.length != 1) {
      throw new RuntimeException(
          "Returned ThreadInfo[] of length=" + infos.length + ". Expected to be 1.");
    }
    thread.checkThreadInfo(infos[0]);

    boolean found = false;
    infos = mbean.dumpAllThreads(true, true);
    for (ThreadInfo ti : infos) {
      if (ti.getThreadId() == thread.getId()) {
        thread.checkThreadInfo(ti);
        found = true;
      }
    }

    if (!found) {
      throw new RuntimeException("No ThreadInfo found for MyThread");
    }

    System.out.println("Test passed");
  }
Exemplo n.º 18
0
  /**
   * Returns an instance of a <b>unicast</b> RTP session. Following this you should adjust any
   * settings and then register your application.
   *
   * <p>The sockets should have external ip addresses, else your CNAME automatically generated CNAMe
   * will be bad.
   *
   * @param rtpSocket UDP socket to receive RTP communication on
   * @param rtcpSocket UDP socket to receive RTCP communication on, null if none.
   */
  public RTPSession(DatagramSocket rtpSocket, DatagramSocket rtcpSocket) {
    mcSession = false;
    rtpSock = rtpSocket;
    this.generateCNAME();
    this.generateSsrc();
    this.rtcpSession = new RTCPSession(this, rtcpSocket);

    // The sockets are not always imediately available?
    try {
      Thread.sleep(1);
    } catch (InterruptedException e) {
      System.out.println("RTPSession sleep failed");
    }
  }
Exemplo n.º 19
0
  /** {@inheritDoc} */
  @Override
  public R get(long timeout, TimeUnit unit) throws IgniteCheckedException {
    A.ensure(timeout >= 0, "timeout cannot be negative: " + timeout);
    A.notNull(unit, "unit");

    try {
      return get0(unit.toNanos(timeout));
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();

      throw new IgniteInterruptedCheckedException(
          "Got interrupted while waiting for future to complete.", e);
    }
  }
Exemplo n.º 20
0
 // To be called exactly twice by the child process
 public static void rendezvousChild() {
   try {
     for (int i = 0; i < 100; i++) {
       System.gc();
       System.runFinalization();
       Thread.sleep(50);
     }
     System.out.write((byte) '\n');
     System.out.flush();
     System.in.read();
   } catch (Throwable t) {
     throw new Error(t);
   }
 }
Exemplo n.º 21
0
 // 提供一个线程安全draw()方法来完成取钱操作
 public void draw(double drawAmount) {
   // 加锁
   lock.lock();
   try {
     // 账户余额大于取钱数目
     if (balance >= drawAmount) {
       // 吐出钞票
       System.out.println(Thread.currentThread().getName() + "取钱成功!吐出钞票:" + drawAmount);
       try {
         Thread.sleep(1);
       } catch (InterruptedException ex) {
         ex.printStackTrace();
       }
       // 修改余额
       balance -= drawAmount;
       System.out.println("\t余额为: " + balance);
     } else {
       System.out.println(Thread.currentThread().getName() + "取钱失败!余额不足!");
     }
   } finally {
     // 修改完成,释放锁
     lock.unlock();
   }
 }
Exemplo n.º 22
0
 /**
  * Spins/blocks until node s is fulfilled.
  *
  * @param s the waiting node
  * @param e the comparison value for checking match
  * @param timed true if timed wait
  * @param nanos timeout value
  * @return matched item, or s if cancelled
  */
 Object awaitFulfill(QNode s, Object e, boolean timed, long nanos) {
   /* Same idea as TransferStack.awaitFulfill */
   long lastTime = timed ? System.nanoTime() : 0;
   Thread w = Thread.currentThread();
   int spins = ((head.next == s) ? (timed ? maxTimedSpins : maxUntimedSpins) : 0);
   for (; ; ) {
     if (w.isInterrupted()) s.tryCancel(e);
     Object x = s.item;
     if (x != e) return x;
     if (timed) {
       long now = System.nanoTime();
       nanos -= now - lastTime;
       lastTime = now;
       if (nanos <= 0) {
         s.tryCancel(e);
         continue;
       }
     }
     if (spins > 0) --spins;
     else if (s.waiter == null) s.waiter = w;
     else if (!timed) LockSupport.park(this);
     else if (nanos > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanos);
   }
 }
Exemplo n.º 23
0
  /**
   * Returns an instance of a <b>multicast</b> RTP session. Following this you should register your
   * application.
   *
   * <p>The sockets should have external ip addresses, else your CNAME automatically generated CNAMe
   * will be bad.
   *
   * @param rtpSock a multicast socket to receive RTP communication on
   * @param rtcpSock a multicast socket to receive RTP communication on
   * @param multicastGroup the multicast group that we want to communicate with.
   */
  public RTPSession(MulticastSocket rtpSock, MulticastSocket rtcpSock, InetAddress multicastGroup)
      throws Exception {
    mcSession = true;
    rtpMCSock = rtpSock;
    mcGroup = multicastGroup;
    rtpMCSock.joinGroup(mcGroup);
    rtcpSock.joinGroup(mcGroup);
    this.generateCNAME();
    this.generateSsrc();
    this.rtcpSession = new RTCPSession(this, rtcpSock, mcGroup);

    // The sockets are not always imediately available?
    try {
      Thread.sleep(1);
    } catch (InterruptedException e) {
      System.out.println("RTPSession sleep failed");
    }
  }
    public void run() {
      while (running) {
        try {
          update();
        } catch (MVRuntimeException e) {
          Log.exception("ProximityTracker.Updater.run caught MVRuntimeException", e);
        } catch (Exception e) {
          Log.exception("ProximityTracker.Updater.run caught exception", e);
        }

        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          Log.warn("Updater: " + e);
          e.printStackTrace();
        }
      }
    }
  public static void main(String[] args) {
    final AttemptLocking al = new AttemptLocking();
    al.untimed(); // True -- lock is available
    al.timed(); // True -- lock is available
    // Now create a separate task to grab the lock:
    new Thread() {
      {
        setDaemon(true);
      }

      public void run() {
        al.lock.lock();
        System.out.println("acquired");
      }
    }.start();
    Thread.yield(); // Give the 2nd task a chance
    al.untimed(); // False -- lock grabbed by task
    al.timed(); // False -- lock grabbed by task
  }
Exemplo n.º 26
0
  public static void main(String[] args) throws Exception {
    int maxThreads = 5;
    if (args.length > 0) maxThreads = Integer.parseInt(args[0]);

    print = true;

    for (int i = 2; i <= maxThreads; i += (i + 1) >>> 1) {
      System.out.print("Threads: " + i);
      try {
        new FutureLoop(i).test();
      } catch (BrokenBarrierException bb) {
        // OK; ignore
      } catch (ExecutionException ee) {
        // OK; ignore
      }
      Thread.sleep(TIMEOUT);
    }
    pool.shutdown();
    if (!pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)) throw new Error();
  }
Exemplo n.º 27
0
  private boolean addConnectionIfUnderMaximum() {

    // First, make sure we don't cross the allowed limit of open connections
    for (; ; ) {
      int opened = open.get();
      if (opened >= options().getMaxConnectionsPerHost(hostDistance)) return false;

      if (open.compareAndSet(opened, opened + 1)) break;
    }

    if (isShutdown()) {
      open.decrementAndGet();
      return false;
    }

    // Now really open the connection
    try {
      connections.add(manager.connectionFactory().open(host));
      signalAvailableConnection();
      return true;
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      // Skip the open but ignore otherwise
      open.decrementAndGet();
      return false;
    } catch (ConnectionException e) {
      open.decrementAndGet();
      logger.debug("Connection error to {} while creating additional connection", host);
      if (host.getMonitor().signalConnectionFailure(e)) shutdown();
      return false;
    } catch (AuthenticationException e) {
      // This shouldn't really happen in theory
      open.decrementAndGet();
      logger.error(
          "Authentication error while creating additional connection (error is: {})",
          e.getMessage());
      shutdown();
      return false;
    }
  }
Exemplo n.º 28
0
  private Connection waitForConnection(long timeout, TimeUnit unit)
      throws ConnectionException, TimeoutException {
    long start = System.nanoTime();
    long remaining = timeout;
    do {
      try {
        awaitAvailableConnection(remaining, unit);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        // If we're interrupted fine, check if there is a connection available but stop waiting
        // otherwise
        timeout = 0; // this will make us stop the loop if we don't get a connection right away
      }

      if (isShutdown()) throw new ConnectionException(host.getAddress(), "Pool is shutdown");

      int minInFlight = Integer.MAX_VALUE;
      Connection leastBusy = null;
      for (Connection connection : connections) {
        int inFlight = connection.inFlight.get();
        if (inFlight < minInFlight) {
          minInFlight = inFlight;
          leastBusy = connection;
        }
      }

      while (true) {
        int inFlight = leastBusy.inFlight.get();

        if (inFlight >= Connection.MAX_STREAM_PER_CONNECTION) break;

        if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) return leastBusy;
      }

      remaining = timeout - Cluster.timeSince(start, unit);
    } while (remaining > 0);

    throw new TimeoutException();
  }
Exemplo n.º 29
0
  /** {@inheritDoc} */
  @Override
  public R get() throws IgniteCheckedException {
    try {
      if (endTime == 0) {
        if (ignoreInterrupts) acquireShared(0);
        else acquireSharedInterruptibly(0);
      }

      if (getState() == CANCELLED)
        throw new IgniteFutureCancelledCheckedException("Future was cancelled: " + this);

      assert resFlag != 0;

      if (resFlag == ERR) throw U.cast((Throwable) res);

      return (R) res;
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();

      throw new IgniteInterruptedCheckedException(e);
    }
  }
Exemplo n.º 30
0
  public void run() {

    System.out.println("Starting " + name);

    try {
      // First, lock count.
      System.out.println(name + " is waiting to lock count.");
      lock.lock();
      System.out.println(name + " is locking count.");

      Shared2.count++;
      System.out.println(name + ": " + Shared2.count);

      // Now, allow a context switch -- if possible.
      System.out.println(name + " is sleeping.");
      Thread.sleep(1000);
    } catch (InterruptedException exc) {
      System.out.println(exc);
    } finally {
      // Unlock
      System.out.println(name + " is unlocking count.");
      lock.unlock();
    }
  }