/** addAndGet adds given value to current, and returns current value */
 public void testAddAndGet() {
   AtomicLong ai = new AtomicLong(1);
   assertEquals(3, ai.addAndGet(2));
   assertEquals(3, ai.get());
   assertEquals(-1, ai.addAndGet(-4));
   assertEquals(-1, ai.get());
 }
 /** getAndAdd returns previous value and adds given value */
 public void testGetAndAdd() {
   AtomicLong ai = new AtomicLong(1);
   assertEquals(1, ai.getAndAdd(2));
   assertEquals(3, ai.get());
   assertEquals(3, ai.getAndAdd(-4));
   assertEquals(-1, ai.get());
 }
 /** repeated weakCompareAndSet succeeds in changing value when equal to expected */
 public void testWeakCompareAndSet() {
   AtomicLong ai = new AtomicLong(1);
   while (!ai.weakCompareAndSet(1, 2)) ;
   while (!ai.weakCompareAndSet(2, -4)) ;
   assertEquals(-4, ai.get());
   while (!ai.weakCompareAndSet(-4, 7)) ;
   assertEquals(7, ai.get());
 }
 /** get returns the last value set */
 public void testGetSet() {
   AtomicLong ai = new AtomicLong(1);
   assertEquals(1, ai.get());
   ai.set(2);
   assertEquals(2, ai.get());
   ai.set(-3);
   assertEquals(-3, ai.get());
 }
 /** incrementAndGet increments and returns current value */
 public void testIncrementAndGet() {
   AtomicLong ai = new AtomicLong(1);
   assertEquals(2, ai.incrementAndGet());
   assertEquals(2, ai.get());
   ai.set(-2);
   assertEquals(-1, ai.incrementAndGet());
   assertEquals(0, ai.incrementAndGet());
   assertEquals(1, ai.incrementAndGet());
   assertEquals(1, ai.get());
 }
 /** compareAndSet succeeds in changing value if equal to expected else fails */
 public void testCompareAndSet() {
   AtomicLong ai = new AtomicLong(1);
   assertTrue(ai.compareAndSet(1, 2));
   assertTrue(ai.compareAndSet(2, -4));
   assertEquals(-4, ai.get());
   assertFalse(ai.compareAndSet(-5, 7));
   assertFalse((7 == ai.get()));
   assertTrue(ai.compareAndSet(-4, 7));
   assertEquals(7, ai.get());
 }
 /** decrementAndGet decrements and returns current value */
 public void testDecrementAndGet() {
   AtomicLong ai = new AtomicLong(1);
   assertEquals(0, ai.decrementAndGet());
   assertEquals(-1, ai.decrementAndGet());
   assertEquals(-2, ai.decrementAndGet());
   assertEquals(-2, ai.get());
 }
  /** a deserialized serialized atomic holds same value */
  public void testSerialization() {
    AtomicLong l = new AtomicLong();

    try {
      l.set(-22);
      ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
      ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
      out.writeObject(l);
      out.close();

      ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
      ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
      AtomicLong r = (AtomicLong) in.readObject();
      assertEquals(l.get(), r.get());
    } catch (Exception e) {
      unexpectedException();
    }
  }
  /**
   * @param pid PID of the other party.
   * @param size Size of the space.
   * @return Token pair.
   */
  private IgnitePair<String> inOutToken(int pid, int size) {
    while (true) {
      long idx = tokIdxGen.get();

      if (tokIdxGen.compareAndSet(idx, idx + 2))
        return F.pair(
            new File(tokDir, TOKEN_FILE_NAME + idx + "-" + pid + "-" + size).getAbsolutePath(),
            new File(tokDir, TOKEN_FILE_NAME + (idx + 1) + "-" + pid + "-" + size)
                .getAbsolutePath());
    }
  }
Esempio n. 10
0
  private void processResponse(DataInputStream in) throws IOException {
    long requestId = in.readLong();
    Request r = requests.remove(requestId);

    if (r == null) {
      throw new IllegalStateException(
          "Request " + requestId + " is unknown (last request generated was " + nextRequest.get());
    }

    Object o = null;
    if (in.readBoolean()) {
      o = serializerFor(classForName(in.readUTF()), r.getResultDeclaredType()).deserialize(in);
    }
    r.set(o);
  }
  /** Should request -1 for infinite */
  @Test
  public void testRequestFromFinalSubscribeWithoutRequestValue() {
    TestSubscriber<String> s = new TestSubscriber<>();
    final AtomicLong r = new AtomicLong();
    s.onSubscribe(
        new Subscription() {

          @Override
          public void request(long n) {
            r.set(n);
          }

          @Override
          public void cancel() {}
        });
    assertEquals(Long.MAX_VALUE, r.get());
  }
 /** compareAndSet in one thread enables another waiting for value to succeed */
 public void testCompareAndSetInMultipleThreads() {
   final AtomicLong ai = new AtomicLong(1);
   Thread t =
       new Thread(
           new Runnable() {
             public void run() {
               while (!ai.compareAndSet(2, 3)) Thread.yield();
             }
           });
   try {
     t.start();
     assertTrue(ai.compareAndSet(1, 2));
     t.join(LONG_DELAY_MS);
     assertFalse(t.isAlive());
     assertEquals(ai.get(), 3);
   } catch (Exception e) {
     unexpectedException();
   }
 }
  @Test
  public void testRequestFromChainedOperator() {
    TestSubscriber<String> s = new TestSubscriber<>();
    Operator<String, String> o =
        s1 ->
            new Subscriber<String>() {

              @Override
              public void onSubscribe(Subscription a) {
                s1.onSubscribe(a);
              }

              @Override
              public void onComplete() {}

              @Override
              public void onError(Throwable e) {}

              @Override
              public void onNext(String t) {}
            };
    s.request(10);
    Subscriber<? super String> ns = o.apply(s);

    final AtomicLong r = new AtomicLong();
    // set set the producer at the top of the chain (ns) and it should flow through the operator to
    // the (s) subscriber
    // and then it should request up with the value set on the final Subscriber (s)
    ns.onSubscribe(
        new Subscription() {

          @Override
          public void request(long n) {
            r.set(n);
          }

          @Override
          public void cancel() {}
        });
    assertEquals(10, r.get());
  }
  @Test
  public void testRequestToObservable() {
    TestSubscriber<Integer> ts = new TestSubscriber<>();
    ts.request(3);
    final AtomicLong requested = new AtomicLong();
    Observable.<Integer>create(
            s ->
                s.onSubscribe(
                    new Subscription() {

                      @Override
                      public void request(long n) {
                        requested.set(n);
                      }

                      @Override
                      public void cancel() {}
                    }))
        .subscribe(ts);
    assertEquals(3, requested.get());
  }
  @Test
  public void testRequestThroughTakeWhereRequestIsSmallerThanTake() {
    TestSubscriber<Integer> ts = new TestSubscriber<>((Long) null);
    ts.request(3);
    final AtomicLong requested = new AtomicLong();
    Observable.<Integer>create(
            s ->
                s.onSubscribe(
                    new Subscription() {

                      @Override
                      public void request(long n) {
                        requested.set(n);
                      }

                      @Override
                      public void cancel() {}
                    }))
        .take(10)
        .subscribe(ts);
    assertEquals(3, requested.get());
  }
  @Test
  public void testRequestThroughTakeThatReducesRequest() {
    TestSubscriber<Integer> ts = new TestSubscriber<>((Long) null);
    ts.request(3);
    final AtomicLong requested = new AtomicLong();
    Observable.<Integer>create(
            s ->
                s.onSubscribe(
                    new Subscription() {

                      @Override
                      public void request(long n) {
                        requested.set(n);
                      }

                      @Override
                      public void cancel() {}
                    }))
        .take(2)
        .subscribe(ts);

    // FIXME the take now requests Long.MAX_PATH if downstream requests at least the limit
    assertEquals(Long.MAX_VALUE, requested.get());
  }
Esempio n. 17
0
  @Override
  public String getLID(DSLAMSource source)
      throws IOException, TimeoutADManClientException, ADManClientException {
    // Update counters:
    String res = null;
    {
      invokeSyncBeginCount.incrementAndGet();
      long runningCount = invokeSyncRunningCount.incrementAndGet();
      long runningCountMax = invokeSyncRunningCountMax.get();
      if (runningCount > runningCountMax) {
        invokeSyncRunningCountMax.compareAndSet(runningCountMax, runningCount);
      }

      synchronized (invokeBeginFrequencyCounter) {
        invokeBeginFrequencyCounter.increment();
      }
    }

    try {
      res = super.getLID(source);
    } catch (Throwable ex) {
      invokeSyncEndFailureCount.incrementAndGet();
    } finally {
      // Update counters:
      {
        invokeSyncEndCount.incrementAndGet();
        invokeSyncRunningCount.decrementAndGet();

        synchronized (invokeEndFrequencyCounter) {
          invokeEndFrequencyCounter.increment();
        }
      }
    }

    return res;
  }
Esempio n. 18
0
 public AtomicLong combine(AtomicLong x, AtomicLong y) {
   // Not clear whether this is meaningful:
   return new AtomicLong(x.addAndGet(y.get()));
 }
  @Test
  public void testRequestFromDecoupledOperatorThatRequestsN() {
    TestSubscriber<String> s = new TestSubscriber<>();
    final AtomicLong innerR = new AtomicLong();
    Operator<String, String> o =
        child -> {
          // we want to decouple the chain so set our own Producer on the child instead of it coming
          // from the parent
          child.onSubscribe(
              new Subscription() {

                @Override
                public void request(long n) {
                  innerR.set(n);
                }

                @Override
                public void cancel() {}
              });

          AsyncObserver<String> as =
              new AsyncObserver<String>() {

                @Override
                protected void onStart() {
                  // we request 99 up to the parent
                  request(99);
                }

                @Override
                public void onComplete() {}

                @Override
                public void onError(Throwable e) {}

                @Override
                public void onNext(String t) {}
              };
          return as;
        };
    s.request(10);
    Subscriber<? super String> ns = o.apply(s);

    final AtomicLong r = new AtomicLong();
    // set set the producer at the top of the chain (ns) and it should flow through the operator to
    // the (s) subscriber
    // and then it should request up with the value set on the final Subscriber (s)
    ns.onSubscribe(
        new Subscription() {

          @Override
          public void request(long n) {
            r.set(n);
          }

          @Override
          public void cancel() {}
        });
    assertEquals(99, r.get());
    assertEquals(10, innerR.get());
  }
Esempio n. 20
0
    /**
     * @param time Test time.
     * @param writers Number of writers threads.
     * @throws Exception If failed.
     */
    public void testQueue(long time, int writers) throws Exception {
      System.out.println("Start test [writers=" + writers + ", time=" + time + "]");

      Thread rdr =
          new Thread() {
            @SuppressWarnings({"InfiniteLoopStatement", "unchecked"})
            @Override
            public void run() {
              try {
                while (true) {
                  Future fut;

                  while ((fut = queue.poll()) != null) {
                    qSize.decrementAndGet();

                    fut.onDone(true);
                  }

                  long size = qSize.get();

                  if (size == 0) {
                    synchronized (mux) {
                      while (queue.isEmpty()) {
                        mux.wait();
                      }
                    }
                  }
                }
              } catch (InterruptedException ignore) {
              }
            }
          };

      rdr.start();

      List<Thread> putThreads = new ArrayList<>();

      for (int i = 0; i < writers; i++) {
        putThreads.add(
            new Thread() {
              @SuppressWarnings("CallToNotifyInsteadOfNotifyAll")
              @Override
              public void run() {
                try {
                  while (!stop) {
                    long id = cnt.incrementAndGet();

                    Future<Boolean> fut = new Future<Boolean>(new Message(id));

                    queue.offer(fut);

                    long size = qSize.incrementAndGet();

                    if (size == 1) {
                      synchronized (mux) {
                        mux.notify();
                      }
                    }

                    Boolean res = fut.get();

                    if (!res) {
                      System.out.println("Error");
                    }
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });
      }

      for (Thread t : putThreads) t.start();

      Thread.sleep(time);

      stop = true;

      for (Thread t : putThreads) t.join();

      rdr.interrupt();

      rdr.join();

      System.out.println("Total: " + cnt.get());

      System.gc();
      System.gc();
      System.gc();
    }
 /** default constructed initializes to zero */
 public void testConstructor2() {
   AtomicLong ai = new AtomicLong();
   assertEquals(0, ai.get());
 }