@Test
 public void afterIsRunAfterFailure() throws Exception {
   for (int i = 0; i < 2; i++) {
     AtomicInteger count = new AtomicInteger();
     TestSuite suite =
         TestSuite.create("my_suite")
             .test(
                 "my_test",
                 context -> {
                   count.compareAndSet(0, 1);
                   context.fail("the_message");
                 });
     if (i == 0) {
       suite = suite.after(context -> count.compareAndSet(1, 2));
     } else {
       suite = suite.afterEach(context -> count.compareAndSet(1, 2));
     }
     TestReporter reporter = new TestReporter();
     run(suite, reporter);
     reporter.await();
     assertEquals(2, count.get());
     assertEquals(0, reporter.exceptions.size());
     assertEquals(1, reporter.results.size());
     assertEquals("my_test", reporter.results.get(0).name());
     assertTrue(reporter.results.get(0).failed());
     assertEquals("the_message", reporter.results.get(0).failure().message());
   }
 }
 @Test
 public void failAfter() throws Exception {
   for (int i = 0; i < 2; i++) {
     AtomicInteger count = new AtomicInteger();
     int val = i;
     TestSuite suite =
         TestSuite.create("my_suite")
             .test("my_test_1", context -> count.compareAndSet(0, 1))
             .test(
                 "my_test_2",
                 context -> {
                   if (val == 0) {
                     count.compareAndSet(1, 2);
                   } else {
                     count.compareAndSet(2, 3);
                   }
                 });
     if (i == 0) {
       suite =
           suite.after(
               context -> {
                 count.incrementAndGet();
                 context.fail("the_message");
               });
     } else {
       AtomicBoolean failed = new AtomicBoolean();
       suite =
           suite.afterEach(
               context -> {
                 count.incrementAndGet();
                 if (failed.compareAndSet(false, true)) {
                   context.fail("the_message");
                 }
               });
     }
     TestReporter reporter = new TestReporter();
     run(suite, reporter);
     reporter.await();
     if (i == 0) {
       assertEquals(3, count.get());
       assertEquals(1, reporter.exceptions.size());
       assertEquals(2, reporter.results.size());
       assertEquals("my_test_1", reporter.results.get(0).name());
       assertTrue(reporter.results.get(0).succeeded());
       assertEquals("my_test_2", reporter.results.get(1).name());
       assertTrue(reporter.results.get(1).succeeded());
     } else {
       assertEquals(4, count.get());
       assertEquals(0, reporter.exceptions.size());
       assertEquals(2, reporter.results.size());
       assertEquals("my_test_1", reporter.results.get(0).name());
       assertTrue(reporter.results.get(0).failed());
       assertEquals("my_test_2", reporter.results.get(1).name());
       assertTrue(reporter.results.get(1).succeeded());
     }
   }
 }
 /** compareAndSet succeeds in changing value if equal to expected else fails */
 public void testCompareAndSet() {
   AtomicInteger ai = new AtomicInteger(1);
   assertTrue(ai.compareAndSet(1, 2));
   assertTrue(ai.compareAndSet(2, -4));
   assertEquals(-4, ai.get());
   assertFalse(ai.compareAndSet(-5, 7));
   assertEquals(-4, ai.get());
   assertTrue(ai.compareAndSet(-4, 7));
   assertEquals(7, ai.get());
 }
Example #4
0
 @Override
 public void run() {
   if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) {
     throw new IllegalStateException("Spider is already running!");
   }
   checkComponent();
   if (startUrls != null) {
     for (String startUrl : startUrls) {
       scheduler.push(new Request(startUrl), this);
     }
   }
   Request request = scheduler.poll(this);
   // singel thread
   if (executorService == null) {
     while (request != null) {
       processRequest(request);
       request = scheduler.poll(this);
     }
   } else {
     // multi thread
     final AtomicInteger threadAlive = new AtomicInteger(0);
     while (true) {
       if (request == null) {
         // when no request found but some thread is alive, sleep a while.
         try {
           Thread.sleep(100);
         } catch (InterruptedException e) {
         }
       } else {
         final Request requestFinal = request;
         threadAlive.incrementAndGet();
         executorService.execute(
             new Runnable() {
               @Override
               public void run() {
                 processRequest(requestFinal);
                 threadAlive.decrementAndGet();
               }
             });
       }
       request = scheduler.poll(this);
       if (threadAlive.get() == 0) {
         request = scheduler.poll(this);
         if (request == null) {
           break;
         }
       }
     }
     executorService.shutdown();
   }
   stat.compareAndSet(STAT_RUNNING, STAT_STOPPED);
   // release some resources
   destroy();
 }
 @Test
 public void runAfter() throws Exception {
   for (int i = 0; i < 2; i++) {
     AtomicInteger count = new AtomicInteger();
     AtomicBoolean sameContext = new AtomicBoolean();
     int val = i;
     TestSuite suite =
         TestSuite.create("my_suite")
             .test(
                 "my_test_1",
                 context -> {
                   count.compareAndSet(0, 1);
                 })
             .test(
                 "my_test_2",
                 context -> {
                   if (val == 0) {
                     count.compareAndSet(1, 2);
                   } else {
                     count.compareAndSet(2, 3);
                   }
                 });
     if (i == 0) {
       suite =
           suite.after(
               context -> {
                 sameContext.set(checkTest(context));
                 count.incrementAndGet();
               });
     } else {
       suite =
           suite.afterEach(
               context -> {
                 sameContext.set(checkTest(context));
                 count.incrementAndGet();
               });
     }
     TestReporter reporter = new TestReporter();
     run(suite, reporter);
     reporter.await();
     assertEquals(i == 0 ? 3 : 4, count.get());
     assertTrue(sameContext.get());
     assertEquals(0, reporter.exceptions.size());
     assertEquals(2, reporter.results.size());
     assertEquals("my_test_1", reporter.results.get(0).name());
     assertTrue(reporter.results.get(0).succeeded());
     assertEquals("my_test_2", reporter.results.get(1).name());
     assertTrue(reporter.results.get(1).succeeded());
   }
 }
Example #6
0
  protected final void onRunEnded() {
    for (; ; ) {
      if (_state.get() == RUNNING) {
        if (_state.compareAndSet(RUNNING, IDLE)) break;
      } else {
        if (Debug.ENABLED) Debug.assertion(_state.get() == RUNNING_SCHEDULED);

        if (_state.compareAndSet(RUNNING_SCHEDULED, SCHEDULED)) {
          startRun();
          break;
        }
      }
    }
  }
Example #7
0
  /**
   * Updates statistics to reflect that a session with a given "alive time" has been expired.
   *
   * @param sessionAliveTime number of ms from when the session was created to when it was expired.
   */
  protected void sessionExpired(int sessionAliveTime) {
    int current = maxAliveTime.get();
    while (sessionAliveTime > current) {
      if (maxAliveTime.compareAndSet(current, sessionAliveTime)) break;
      else current = maxAliveTime.get();
    }

    expiredCounter_.incrementAndGet();
    int newAverage;
    do {
      int expCount = expiredCounter_.get();
      current = averageAliveTime.get();
      newAverage = ((current * (expCount - 1)) + sessionAliveTime) / expCount;
    } while (averageAliveTime.compareAndSet(current, newAverage) == false);
  }
 /**
  * Tries to grow array to accommodate at least one more element (but normally expand by about
  * 50%), giving up (allowing retry) on contention (which we expect to be rare). Call only while
  * holding lock.
  *
  * @param array the heap array
  * @param oldCap the length of the array
  */
 private void tryGrow(Object[] array, int oldCap) {
   lock.unlock(); // must release and then re-acquire main lock
   Object[] newArray = null;
   if (allocationSpinLock.get() == 0 && allocationSpinLock.compareAndSet(0, 1)) {
     try {
       int newCap =
           oldCap
               + ((oldCap < 64)
                   ? (oldCap + 2)
                   : // grow faster if small
                   (oldCap >> 1));
       if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
         int minCap = oldCap + 1;
         if (minCap < 0 || minCap > MAX_ARRAY_SIZE) throw new OutOfMemoryError();
         newCap = MAX_ARRAY_SIZE;
       }
       if (newCap > oldCap && deque == array) newArray = new Object[newCap];
     } finally {
       allocationSpinLock.set(0);
     }
   }
   if (newArray == null) // back off if another thread is allocating
   Thread.yield();
   lock.lock();
   if (newArray != null && deque == array) {
     deque = newArray;
     System.arraycopy(array, 0, newArray, 0, oldCap);
   }
 }
Example #9
0
 protected void onConnectionOpened() {
   if (mConnectionStatus.compareAndSet(MAVLINK_CONNECTING, MAVLINK_CONNECTED)) {
     mLogger.logInfo(TAG, "Starting manager thread.");
     mTaskThread = new Thread(mManagerTask, "MavLinkConnection-Manager Thread");
     mTaskThread.start();
   }
 }
  /** {@inheritDoc} */
  @Override
  protected Collection<E> dequeue0(int cnt) {
    WindowHolder tup = ref.get();

    AtomicInteger size = tup.size();
    Collection<T> evts = tup.collection();

    Collection<E> resCol = new ArrayList<>(cnt);

    while (true) {
      int curSize = size.get();

      if (curSize > 0) {
        if (size.compareAndSet(curSize, curSize - 1)) {
          E res = pollInternal(evts, tup.set());

          if (res != null) {
            resCol.add(res);

            if (resCol.size() >= cnt) return resCol;
          } else {
            size.incrementAndGet();

            return resCol;
          }
        }
      } else return resCol;
    }
  }
Example #11
0
 @Override
 public boolean commit() {
   try {
     if (!writeSet.isEmpty()) {
       int v = status.get();
       int s = v & STATUS_MASK;
       if (s == TX_ACTIVE && status.compareAndSet(v, v + (TX_COMMITTING - TX_ACTIVE))) {
         long newClock = clock.incrementAndGet();
         if (newClock != startTime.get() + 1 && !readSet.validate(this, id)) {
           rollback0();
           return false;
         }
         // Write values and release locks
         writeSet.commit(newClock);
         status.set(v + (TX_COMMITTED - TX_ACTIVE));
       } else {
         // We have been killed: wait for our locks to have been released
         while (s != TX_ABORTED) s = status.get() & STATUS_MASK;
         return false;
       }
     } else {
       // No need to set status to COMMITTED (we cannot be killed with an empty write set)
     }
     attempts = 0;
     return true;
   } finally {
     if (irrevocableState) {
       irrevocableState = false;
       irrevocableAccessLock.writeLock().unlock();
     } else {
       irrevocableAccessLock.readLock().unlock();
     }
   }
 }
 /**
  * Computes the index of the next balancer to retrieve. Adaptation of the {@link AtomicInteger}
  * incrementAndGet() code.
  *
  * @return
  */
 private int getNextIndex() {
   for (; ; ) {
     int current = index.get();
     int next = (current == balancers.size() ? 1 : current + 1);
     if (index.compareAndSet(current, next)) return next - 1;
   }
 }
Example #13
0
  public static boolean lock(Object lockIndex, Set<Object> contextLocks)
      throws TransactionException {
    AtomicInteger lock = getLock(lockIndex);
    int val = lock.get();
    if ((val & REMOTE) != 0) { // is remote lock
      Logger.debug("Remotly Locked object");
      return false;
    }

    //		final int selfLockIndex = lockIndex>>>DIVIDE_8;
    //		final byte selfLockByte = contextLocks[selfLockIndex];
    //		final byte selfLockBit = (byte)(1 << (lockIndex & MODULE_8));

    if ((val & LOCK) != 0) { // is already locked?

      if (contextLocks.contains(lockIndex)) // check for self locking
      return true;
      Logger.debug("Locally Locked object");
      throw FAILURE_EXCEPTION;
    }

    boolean isLocked = lock.compareAndSet(val, val | LOCK);

    if (!isLocked) {
      Logger.debug("Being Locked object");
      throw FAILURE_EXCEPTION;
    }

    contextLocks.add(lockIndex); // mark in self locks

    Logger.debug("Successful Locked object");
    return true;
  }
Example #14
0
 @Test
 public void runTest() {
   AtomicInteger count = new AtomicInteger();
   AtomicBoolean sameContext = new AtomicBoolean();
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 sameContext.set(checkTest(context));
                 count.compareAndSet(0, 1);
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   reporter.await();
   assertTrue(sameContext.get());
   assertEquals(1, count.get());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertTrue(result.succeeded());
   assertFalse(result.failed());
   assertNull(result.failure());
 }
Example #15
0
  private boolean addConnectionIfUnderMaximum() {
    for (; ; ) {
      int opened = open.get();
      if (opened >= options().getMaxConnectionsPerHost()) return false;

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

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

    try {
      connections.add(session.connectionFactory().open(this));
      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);
      return false;
    }
  }
 // Alternative implementation as increment but just make the
 // implementation explicit
 public int incrementLongVersion() {
   int oldValue = value.get();
   while (!value.compareAndSet(oldValue, oldValue + 1)) {
     oldValue = value.get();
   }
   return oldValue + 1;
 }
Example #17
0
  /** Start a new connection. Returns true if the connection can be started. */
  public boolean startConnection() {
    State state = _state.get();

    if (state.isActive()) {
      // when active, always start a connection

      _connectionCount.incrementAndGet();

      return true;
    }

    long now = CurrentTime.currentTime();
    long lastFailTime = _lastFailTime;
    long recoverTimeout = _dynamicRecoverTimeout.get();

    if (now < lastFailTime + recoverTimeout) {
      // if the fail recover hasn't timed out, return false
      return false;
    }

    // when fail, only start a single connection
    int count;

    do {
      count = _connectionCount.get();

      if (count > 0) {
        return false;
      }
    } while (!_connectionCount.compareAndSet(count, count + 1));

    return true;
  }
Example #18
0
  protected IStream createRemoteStream(int streamId) {
    // SPEC: exceeding max concurrent streams is treated as stream error.
    while (true) {
      int remoteCount = remoteStreamCount.get();
      int maxCount = getMaxRemoteStreams();
      if (maxCount >= 0 && remoteCount >= maxCount) {
        reset(new ResetFrame(streamId, ErrorCode.REFUSED_STREAM_ERROR.code), Callback.NOOP);
        return null;
      }
      if (remoteStreamCount.compareAndSet(remoteCount, remoteCount + 1)) break;
    }

    IStream stream = newStream(streamId, false);

    // SPEC: duplicate stream is treated as connection error.
    if (streams.putIfAbsent(streamId, stream) == null) {
      updateLastStreamId(streamId);
      stream.setIdleTimeout(getStreamIdleTimeout());
      flowControl.onStreamCreated(stream);
      if (LOG.isDebugEnabled()) LOG.debug("Created remote {}", stream);
      return stream;
    } else {
      close(ErrorCode.PROTOCOL_ERROR.code, "duplicate_stream", Callback.NOOP);
      return null;
    }
  }
Example #19
0
  public void newCharacter(CharacterEvent ce) {
    int oldChar2type;

    // Previous character not typed correctly - 1 point penalty
    if (ce.source == generator.get()) {
      oldChar2type = char2type.getAndSet(ce.character); // 接收随机字母

      if (oldChar2type != -1) {
        score.decrementAndGet();
        setScore();
      }
    }
    // If character is extraneous - 1 point penalty
    // If character does not match - 1 point penalty
    else if (ce.source == typist.get()) {
      // 在此有个假设:即正在使用的该变量值不会被变更且程序代码完成时也是如此
      // 所有已经被我们设定的具有特定值的变量就应当是那个值。
      while (true) {
        oldChar2type = char2type.get(); // 获取上次已接收到的随机字母

        if (oldChar2type != ce.character) { // ce.character是用户输入的字母,现在作比较
          score.decrementAndGet();
          break;
        } else if (char2type.compareAndSet(oldChar2type, -1)) {
          score.incrementAndGet();
          break;
        }
      }

      setScore();
    }
  }
  /**
   * Poll evicted internal implementation.
   *
   * @return Evicted element.
   */
  @Nullable
  private E pollEvictedInternal() {
    WindowHolder tup = ref.get();

    AtomicInteger size = tup.size();

    while (true) {
      int curSize = size.get();

      if (curSize > maxSize) {
        if (size.compareAndSet(curSize, curSize - 1)) {
          E evt = pollInternal(tup.collection(), tup.set());

          if (evt != null) return evt;
          else {
            // No actual events in queue, it means that other thread is just adding event.
            // return null as it is a concurrent add call.
            size.incrementAndGet();

            return null;
          }
        }
      } else return null;
    }
  }
  /** Handles size after put. */
  private void onPut() {
    cnt.incrementAndGet();

    int c;

    while ((c = cnt.get()) > max) {
      // Decrement count.
      if (cnt.compareAndSet(c, c - 1)) {
        try {
          K key = firstEntry().getKey();

          V val;

          // Make sure that an element is removed.
          while ((val = super.remove(firstEntry().getKey())) == null) {
            // No-op.
          }

          assert val != null;

          GridInClosure2<K, V> lsnr = this.lsnr;

          // Listener notification.
          if (lsnr != null) lsnr.apply(key, val);
        } catch (NoSuchElementException e1) {
          e1.printStackTrace(); // Should never happen.

          assert false : "Internal error in grid bounded ordered set.";
        }
      }
    }
  }
Example #22
0
 /**
  * Combine this reduction variable with the given value using the given operation. The result is
  * stored back into this reduction variable and is returned.
  *
  * @param value Value.
  * @param op Binary operation.
  * @return (This variable) <I>op</I> (<TT>value</TT>).
  */
 public int reduce(int value, IntegerOp op) {
   for (; ; ) {
     int oldvalue = myValue.get();
     int newvalue = op.op(oldvalue, value);
     if (myValue.compareAndSet(oldvalue, newvalue)) return newvalue;
   }
 }
Example #23
0
  //  Check whether item is available for reading.
  public final boolean check_read() {
    //  Was the value prefetched already? If so, return.
    int h = queue.front_pos();
    if (h != r) return true;

    //  There's no prefetched value, so let us prefetch more values.
    //  Prefetching is to simply retrieve the
    //  pointer from c in atomic fashion. If there are no
    //  items to prefetch, set c to -1 (using compare-and-swap).
    if (c.compareAndSet(h, -1)) {
      // nothing to read, h == r must be the same
    } else {
      // something to have been written
      r = c.get();
    }

    //  If there are no elements prefetched, exit.
    //  During pipe's lifetime r should never be NULL, however,
    //  it can happen during pipe shutdown when items
    //  are being deallocated.
    if (h == r || r == -1) return false;

    //  There was at least one value prefetched.
    return true;
  }
Example #24
0
 @Test
 public void runTestWithAsyncCompletion() throws Exception {
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   AtomicInteger count = new AtomicInteger();
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 count.compareAndSet(0, 1);
                 queue.add(context.async());
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Async async = queue.poll(2, TimeUnit.SECONDS);
   assertEquals(1, count.get());
   assertFalse(reporter.completed());
   completeAsync.accept(async);
   reporter.await();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertTrue(result.succeeded());
   assertFalse(result.failed());
   assertNull(result.failure());
 }
Example #25
0
  protected final void onStarted() {
    if (!_state.compareAndSet(STARTING, IDLE)) {
      if (Debug.ENABLED) Debug.assertion(_state.get() == STARTING_SCHEDULED);

      _state.set(IDLE);
      requestRun();
    }
  }
 /** Notifies all waiting threads */
 private final void atomicNotify(int index) {
   AtomicInteger i = auxStore.getWaiting(index);
   if (!i.compareAndSet(0, 0)) {
     synchronized (i) {
       i.notifyAll();
     }
   }
 }
Example #27
0
 /**
  * Marks a channel as having read the message.
  *
  * @param channel The channel that has read the message
  */
 public void markChannelRead(Channel channel) {
   boolean done = false;
   while (!done) {
     int readOld = read.get();
     int readNew = readOld | channel.getMask();
     done = read.compareAndSet(readOld, readNew);
   }
 }
 public int generateOpaque() {
   int rv = SEQ_NUMBER.incrementAndGet();
   while (rv < 0) {
     SEQ_NUMBER.compareAndSet(rv, 0);
     rv = SEQ_NUMBER.incrementAndGet();
   }
   return rv;
 }
Example #29
0
 /**
  * Establish a mavlink connection. If the connection is successful, it will be reported through
  * the MavLinkConnectionListener interface.
  */
 public void connect() {
   if (mConnectionStatus.compareAndSet(MAVLINK_DISCONNECTED, MAVLINK_CONNECTING)) {
     mLogger.logInfo(TAG, "Starting connection thread.");
     mConnectThread = new Thread(mConnectingTask, "MavLinkConnection-Connecting Thread");
     mConnectThread.start();
     reportConnecting();
   }
 }
Example #30
0
  /**
   * Acquires a permit from this semaphore, only if one is available at the time of invocation.
   *
   * <p>Acquires a permit, if one is available and returns immediately, with the value
   * <tt>true</tt>, reducing the number of available permits by one.
   *
   * <p>If no permit is available then this method will return immediately with the value
   * <tt>false</tt>.
   *
   * <p>Even when this semaphore has been set to use a fair ordering policy, a call to
   * <tt>tryAcquire()</tt> <em>will</em> immediately acquire a permit if one is available, whether
   * or not other threads are currently waiting. This &quot;barging&quot; behavior can be useful in
   * certain circumstances, even though it breaks fairness. If you want to honor the fairness
   * setting, then use {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) } which is
   * almost equivalent (it also detects interruption).
   *
   * @return <tt>true</tt> if a permit was acquired and <tt>false</tt> otherwise.
   */
  public boolean tryAcquire() {
    int oldCount;

    do {
      oldCount = count.get();
    } while (oldCount > 0 && !count.compareAndSet(oldCount, oldCount - 1));

    return (oldCount > 0);
  }