/** longValue returns current value. */ public void testLongValue() { AtomicLong ai = new AtomicLong(); for (int i = -12; i < 6; ++i) { ai.set(i); assertEquals((long) i, ai.longValue()); } }
/** 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()); }
/** floatValue returns current value. */ public void testFloatValue() { AtomicLong ai = new AtomicLong(); for (int i = -12; i < 6; ++i) { ai.set(i); assertEquals((float) i, ai.floatValue()); } }
/** doubleValue returns current value. */ public void testDoubleValue() { AtomicLong ai = new AtomicLong(); for (int i = -12; i < 6; ++i) { ai.set(i); assertEquals((double) i, ai.doubleValue()); } }
/** 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()); }
/** toString returns current value. */ public void testToString() { AtomicLong ai = new AtomicLong(); for (long i = -12; i < 6; ++i) { ai.set(i); assertEquals(ai.toString(), Long.toString(i)); } }
/** * @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()); } }
/** * Creates thread with given {@code name}. * * @param gridName Name of grid this thread is created in. * @param name Thread's name. * @param log Grid logger to use. */ protected GridSpiThread(String gridName, String name, GridLogger log) { super(DFLT_GRP, name + "-#" + cntr.incrementAndGet() + '%' + gridName); assert log != null; this.log = log; }
/** 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 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()); }
/** 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(); } }
private Distributor(ByteArrayConsumer consumer, T root, Class<T> rootFacade) { addDefaultSerializers(); setConsumer(consumer); if (root == null) { rootClient = proxyFor(objectsId.getAndIncrement(), rootFacade); } else { serverFor(root); } }
/** 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()); }
/** 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()); }
@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()); }
/** 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()); }
public ServerObject serverFor(Object o) { ServerObject server = serving.get(o); if (server == null) { server = new ServerObject(objectsId.getAndIncrement(), o); serving.put(o, server); servingById.put(server.getId(), server); } return server; }
protected Request request(long objectId, Method method, Object[] args, boolean expectsResponse) throws IOException { Request r = new Request(this, method, args); long requestId = -1; if (expectsResponse) { requestId = nextRequest.getAndIncrement(); requests.put(requestId, r); } sendRequest(objectId, requestId, r); return r; }
@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()); }
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); }
/** * @param parent Parent entry. * @param nodeId Requesting node ID. * @param otherNodeId Near node ID. * @param otherVer Other version. * @param threadId Requesting thread ID. * @param ver Cache version. * @param timeout Maximum wait time. * @param loc {@code True} if the lock is local. * @param reentry {@code True} if candidate is for reentry. * @param tx Transaction flag. * @param singleImplicit Single-key-implicit-transaction flag. * @param nearLoc Near-local flag. * @param dhtLoc DHT local flag. */ public GridCacheMvccCandidate( GridCacheEntryEx<K, ?> parent, UUID nodeId, @Nullable UUID otherNodeId, @Nullable GridCacheVersion otherVer, long threadId, GridCacheVersion ver, long timeout, boolean loc, boolean reentry, boolean tx, boolean singleImplicit, boolean nearLoc, boolean dhtLoc) { assert nodeId != null; assert ver != null; assert parent != null; this.parent = parent; this.nodeId = nodeId; this.otherNodeId = otherNodeId; this.otherVer = otherVer; this.threadId = threadId; this.ver = ver; this.timeout = timeout; mask(LOCAL, loc); mask(REENTRY, reentry); mask(TX, tx); mask(SINGLE_IMPLICIT, singleImplicit); mask(NEAR_LOCAL, nearLoc); mask(DHT_LOCAL, dhtLoc); ts = U.currentTimeMillis(); id = IDGEN.incrementAndGet(); }
@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; }
/** * @param entries Entries to submit. * @param curFut Current future. * @throws GridInterruptedException If interrupted. */ private void submit(final List<Map.Entry<K, V>> entries, final GridFutureAdapter<Object> curFut) throws GridInterruptedException { assert entries != null; assert !entries.isEmpty(); assert curFut != null; incrementActiveTasks(); GridFuture<Object> fut; if (isLocNode) { fut = ctx.closure() .callLocalSafe( new GridDataLoadUpdateJob<>(ctx, log, cacheName, entries, false, updater), false); locFuts.add(fut); fut.listenAsync( new GridInClosure<GridFuture<Object>>() { @Override public void apply(GridFuture<Object> t) { try { boolean rmv = locFuts.remove(t); assert rmv; curFut.onDone(t.get()); } catch (GridException e) { curFut.onDone(e); } } }); } else { byte[] entriesBytes; try { entriesBytes = ctx.config().getMarshaller().marshal(entries); if (updaterBytes == null) { assert updater != null; updaterBytes = ctx.config().getMarshaller().marshal(updater); } if (topicBytes == null) topicBytes = ctx.config().getMarshaller().marshal(topic); } catch (GridException e) { U.error(log, "Failed to marshal (request will not be sent).", e); return; } GridDeployment dep = null; GridPeerDeployAware jobPda0 = null; if (ctx.deploy().enabled()) { try { jobPda0 = jobPda; assert jobPda0 != null; dep = ctx.deploy().deploy(jobPda0.deployClass(), jobPda0.classLoader()); } catch (GridException e) { U.error( log, "Failed to deploy class (request will not be sent): " + jobPda0.deployClass(), e); return; } if (dep == null) U.warn(log, "Failed to deploy class (request will be sent): " + jobPda0.deployClass()); } long reqId = idGen.incrementAndGet(); fut = curFut; reqs.put(reqId, (GridFutureAdapter<Object>) fut); GridDataLoadRequest<Object, Object> req = new GridDataLoadRequest<>( reqId, topicBytes, cacheName, updaterBytes, entriesBytes, true, dep != null ? dep.deployMode() : null, dep != null ? jobPda0.deployClass().getName() : null, dep != null ? dep.userVersion() : null, dep != null ? dep.participants() : null, dep != null ? dep.classLoaderId() : null, dep == null); try { ctx.io().send(node, TOPIC_DATALOAD, req, PUBLIC_POOL); if (log.isDebugEnabled()) log.debug("Sent request to node [nodeId=" + node.id() + ", req=" + req + ']'); } catch (GridException e) { if (ctx.discovery().alive(node) && ctx.discovery().pingNode(node.id())) ((GridFutureAdapter<Object>) fut).onDone(e); else ((GridFutureAdapter<Object>) fut) .onDone( new GridTopologyException( "Failed to send " + "request (node has left): " + node.id())); } } }
/** getAndSet returns previous value and sets to given value */ public void testGetAndSet() { AtomicLong ai = new AtomicLong(1); assertEquals(1, ai.getAndSet(0)); assertEquals(0, ai.getAndSet(-10)); assertEquals(-10, ai.getAndSet(1)); }
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()); }