public void testCacheStopExpired() throws Exception { ProducerCache cache = new ProducerCache(this, context, 5); cache.start(); assertEquals("Size should be 0", 0, cache.size()); for (int i = 0; i < 8; i++) { Endpoint e = new MyEndpoint(true, i); Producer p = cache.acquireProducer(e); cache.releaseProducer(e, p); } // the eviction is async so force cleanup cache.cleanUp(); assertEquals("Size should be 5", 5, cache.size()); // the eviction listener is async so sleep a bit Thread.sleep(1000); // should have stopped the 3 evicted assertEquals(3, stopCounter.get()); cache.stop(); // should have stopped all 8 assertEquals(8, stopCounter.get()); }
@Test public void bufferDiscardsStreamWhenFull() throws IOException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); Pair<InputStream, List<byte[]>> stream = TestUtils.generateStream(100); MJpegStreamBufferer buffer = new MJpegStreamBufferer(5); AtomicInteger discardedCount = new AtomicInteger(0); buffer.start( new MJpegStreamBufferListener() { @Override public void stopped() { latch.countDown(); } @Override public void streamBuffered(byte[] stream) {} @Override public void streamDiscarded(byte[] stream) { discardedCount.incrementAndGet(); } }, new MJpegStreamIterator(stream.getLeft())); latch.await(); for (int x = 0; x < 5; ++x) { assertThat(buffer.get(), is(stream.getRight().get(x + 95))); } assertNull(buffer.get()); assertThat(discardedCount.get(), is(95)); }
@Override public void handlePerspective( final Message<Event, Object> action, final PerspectiveLayout perspectiveLayout) { if (action.messageBodyEquals(MessageUtil.INIT)) { perspectiveLayout.registerRootComponent(createRoot()); GridPane.setVgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS); GridPane.setHgrow(perspectiveLayout.getRootComponent(), Priority.ALWAYS); // register left panel perspectiveLayout.registerTargetLayoutComponent("content0", this.content1); perspectiveLayout.registerTargetLayoutComponent("content1", this.content2); perspectiveLayout.registerTargetLayoutComponent("content2", this.content3); ApplicationLauncherPerspectiveMessaginTest.latch.countDown(); } else { if (counter.get() > 1) { counter.decrementAndGet(); context.send("id10", "message"); } else { System.out.println("Perspective id12: FINISH"); if (wait.getCount() > 0) wait.countDown(); if (PerspectiveMessagingTestP1.wait.getCount() > 0) context.send("id10", "message"); } } }
public E poll() { final AtomicInteger count = this.count; if (count.get() == 0) return null; Node<E> x = null; final ReentrantLock takeLock = this.takeLock; takeLock.lock(); try { if (count.get() > 0) { x = extract(); if (count.getAndDecrement() > 1) notEmpty.signal(); } } finally { takeLock.unlock(); } if (x != null) { E result = x.item; // temporary clearence x.item = null; x.next = null; return result; } return null; }
private String api_getTokenType(Account account, String token, boolean liveToken) throws Exception { synchronized (account) { try { String tokenType = account.getStringProperty("tokenType", null); if (tokenType != null && liveToken == false) return tokenType; br.getPage("http://cloudzer.net/api/user/jdownloader?access_token=" + token); tokenType = br.getRegex("account_type\":\\s*?\"(premium|free)").getMatch(0); if (tokenType == null) handleErrorCode(br, account, token, true); account.setProperty("tokenType", tokenType); if ("premium".equals(tokenType)) { try { maxPrem.set(-1); account.setMaxSimultanDownloads(-1); account.setConcurrentUsePossible(true); } catch (final Throwable e) { } } else { try { maxPrem.set(1); account.setMaxSimultanDownloads(1); account.setConcurrentUsePossible(false); } catch (final Throwable e) { } } return tokenType; } catch (final PluginException e) { maxPrem.set(-1); account.setProperty("token", null); account.setProperty("tokenType", null); throw e; } } }
protected void allocateBuffers(WebSocket c) throws InterruptedException { if (queuesize.get() >= 2 * decoders.size() + 1) { return; } queuesize.incrementAndGet(); buffers.put(createBuffer()); }
private ProBInstance startProlog() { ProcessHandle processTuple = processProvider.get(); Process process = processTuple.getProcess(); String key = processTuple.getKey(); final BufferedReader stream = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); Map<Class<? extends AbstractCliPattern<?>>, AbstractCliPattern<?>> cliInformation = extractCliInformation(stream); Integer port = ((PortPattern) cliInformation.get(PortPattern.class)).getValue(); Long userInterruptReference = ((InterruptRefPattern) cliInformation.get(InterruptRefPattern.class)).getValue(); ProBConnection connection = new ProBConnection(key, port); try { processCounter.incrementAndGet(); connection.connect(); ProBInstance cli = new ProBInstance( process, stream, userInterruptReference, connection, home, osInfo, processCounter); processes.add(new WeakReference<ProBInstance>(cli)); return cli; } catch (IOException e) { processCounter.decrementAndGet(); logger.error("Error connecting to Prolog binary.", e); return null; } }
/** * Removes the specified element from this set if it is present. More formally, removes an element * {@code e} such that <tt>(o==null ? e==null : o.equals(e))</tt>, if this set * contains such an element. Returns {@code true} if this set contained the element (or * equivalently, if this set changed as a result of the call). (This set will not contain the * element once the call returns.) * * <p>The {@code writeLock} will be locked throughout the entire operation. * * @param elem element to be removed from this set, if present * @return {@code true} if this set contained the specified element */ public synchronized boolean remove(E elem) { final boolean retValue; int localLeftRight = leftRight.get(); // Do the add() in the first Tree, opposite to the one currently // being used by the Read operations. No need to wait. if (localLeftRight == READS_ON_LEFT) { retValue = rightTree.remove(elem); } else { retValue = leftTree.remove(elem); } // Optimization that only works for Sets if (!retValue) return false; // Toggle leftRight and wait for currently running Readers leftRight.set(-localLeftRight); toggleVersionAndScan(); if (-localLeftRight == READS_ON_LEFT) { rightTree.remove(elem); } else { leftTree.remove(elem); } return retValue; }
public void whenNormalOperation(boolean partitionSpecific, boolean remoteCall) { BasicBackPressureService service = newEnabledBackPressureService(); Operation op; if (partitionSpecific) { PartitionSpecificOperation partitionOp = new PartitionSpecificOperation(); partitionOp.setPartitionId(0); op = partitionOp; } else { op = new GenericOperation(); op.setPartitionId(-1); } Connection connection = null; if (remoteCall) { connection = mock(Connection.class); OperationAccessor.setConnection(op, connection); } int expected = SYNC_WINDOW - 1; for (int k = 0; k < SYNC_WINDOW; k++) { boolean result = service.isBackPressureNeeded(op); assertFalse("no back pressure expected", result); AtomicInteger syncDelay = service.getSyncDelay(connection, op.getPartitionId()); assertEquals(expected, syncDelay.get()); expected--; } boolean result = service.isBackPressureNeeded(op); assertTrue("back pressure expected", result); AtomicInteger syncDelay = service.getSyncDelay(connection, op.getPartitionId()); assertValidSyncDelay(syncDelay); }
@Test public void uint16() { Wire wire = createWire(); wire.write().uint16(1); wire.write(BWKey.field1).uint16(2); wire.write(() -> "Test").uint16(3); checkWire( wire, "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊", "[pos: 0, rlim: 22, wlim: 8EiB, cap: 8EiB ] À¢⒈٠Æfield1¢⒉٠ÄTest¢⒊٠", "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊", "[pos: 0, rlim: 17, wlim: 8EiB, cap: 8EiB ] À¢⒈٠º⒈¢⒉٠º²ñ\\u009E⒈¢⒊٠", "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊", "[pos: 0, rlim: 9, wlim: 8EiB, cap: 8EiB ] ¢⒈٠¢⒉٠¢⒊٠"); checkAsText123(wire); // ok as blank matches anything AtomicInteger i = new AtomicInteger(); IntStream.rangeClosed(1, 3) .forEach( e -> { wire.read().uint16(i::set); assertEquals(e, i.get()); }); assertEquals(0, bytes.readRemaining()); // check it's safe to read too much. wire.read(); }
@Test public void int32() { Wire wire = createWire(); wire.write().int32(1); wire.write(BWKey.field1).int32(2); wire.write(() -> "Test").int32(3); checkWire( wire, "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊", "[pos: 0, rlim: 28, wlim: 8EiB, cap: 8EiB ] À¦⒈٠٠٠Æfield1¦⒉٠٠٠ÄTest¦⒊٠٠٠", "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊", "[pos: 0, rlim: 23, wlim: 8EiB, cap: 8EiB ] À¦⒈٠٠٠º⒈¦⒉٠٠٠º²ñ\\u009E⒈¦⒊٠٠٠", "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊", "[pos: 0, rlim: 15, wlim: 8EiB, cap: 8EiB ] ¦⒈٠٠٠¦⒉٠٠٠¦⒊٠٠٠"); checkAsText123(wire); // ok as blank matches anything AtomicInteger i = new AtomicInteger(); IntStream.rangeClosed(1, 3) .forEach( e -> { wire.read().int32(i::set); assertEquals(e, i.get()); }); assertEquals(0, bytes.readRemaining()); // check it's safe to read too much. wire.read(); }
@Test public void int8() { Wire wire = createWire(); wire.write().int8((byte) 1); wire.write(BWKey.field1).int8((byte) 2); wire.write(() -> "Test").int8((byte) 3); checkWire( wire, "[pos: 0, rlim: 16, wlim: 8EiB, cap: 8EiB ] À⒈Æfield1⒉ÄTest⒊", "[pos: 0, rlim: 19, wlim: 8EiB, cap: 8EiB ] À¤⒈Æfield1¤⒉ÄTest¤⒊", "[pos: 0, rlim: 11, wlim: 8EiB, cap: 8EiB ] À⒈º⒈⒉º²ñ\\u009E⒈⒊", "[pos: 0, rlim: 14, wlim: 8EiB, cap: 8EiB ] À¤⒈º⒈¤⒉º²ñ\\u009E⒈¤⒊", "[pos: 0, rlim: 3, wlim: 8EiB, cap: 8EiB ] ⒈⒉⒊", "[pos: 0, rlim: 6, wlim: 8EiB, cap: 8EiB ] ¤⒈¤⒉¤⒊"); checkAsText123(wire); // ok as blank matches anything AtomicInteger i = new AtomicInteger(); IntStream.rangeClosed(1, 3) .forEach( e -> { wire.read().int8(i::set); assertEquals(e, i.get()); }); assertEquals(0, bytes.readRemaining()); // check it's safe to read too much. wire.read(); }
/** * 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; } }
public void testReleaseProducerInvokesStopAndShutdownByNonSingletonProducers() throws Exception { ProducerCache cache = new ProducerCache(this, context, 1); cache.start(); assertEquals("Size should be 0", 0, cache.size()); for (int i = 0; i < 3; i++) { Endpoint e = new MyEndpoint(false, i); Producer p = cache.acquireProducer(e); cache.releaseProducer(e, p); } assertEquals("Size should be 0", 0, cache.size()); // should have stopped all 3 assertEquals(3, stopCounter.get()); // should have shutdown all 3 assertEquals(3, shutdownCounter.get()); cache.stop(); // no more stop after stopping the cache assertEquals(3, stopCounter.get()); // no more shutdown after stopping the cache assertEquals(3, shutdownCounter.get()); }
public synchronized PageBufferClientStatus getStatus() { String state; if (closed) { state = "closed"; } else if (future != null) { state = "running"; } else if (scheduled) { state = "scheduled"; } else if (completed) { state = "completed"; } else { state = "queued"; } String httpRequestState = "not scheduled"; if (future != null) { httpRequestState = future.getState(); } long rejectedRows = rowsRejected.get(); int rejectedPages = pagesRejected.get(); return new PageBufferClientStatus( location, state, lastUpdate, rowsReceived.get(), pagesReceived.get(), rejectedRows == 0 ? OptionalLong.empty() : OptionalLong.of(rejectedRows), rejectedPages == 0 ? OptionalInt.empty() : OptionalInt.of(rejectedPages), requestsScheduled.get(), requestsCompleted.get(), requestsFailed.get(), httpRequestState); }
@Test public void testIllegalToCreateChildEvenWithEdgeToEnd() { final AtomicInteger integer = new AtomicInteger(); try { Intervals.inline( new AbstractTask("a") { @Override public void run(Interval subinterval) { final Interval a = subinterval.newAsyncChild(new TestInterval.IncTask("a", integer)); subinterval.newAsyncChild( new AbstractTask("b") { @Override public void run(Interval current) { a.newAsyncChild(new TestInterval.IncTask("a1", integer, 10)); } }); } }); Assert.fail(); } catch (RethrownException e) { Assert.assertTrue(e.getCause() instanceof IntervalException.MustHappenBefore); } Assert.assertEquals(1, integer.get()); // a should execute }
private void triggerSnapshotIfRequired( String type, Object aggregateIdentifier, final AtomicInteger eventCount) { if (eventCount.get() > trigger) { snapshotter.scheduleSnapshot(type, aggregateIdentifier); eventCount.set(1); } }
@Override public void onInbound(InboundInterceptorContext context) throws Exception { if (context.request().requestType() == RequestType.CREATE) { ResourceResponse response = new DefaultResourceResponse( context.request(), ResourceResponse.ResponseType.CREATED, new Resource() { @Override public Resource parent() { return null; } @Override public String id() { return "mock"; } }); ResourceState state = new DefaultResourceState(); state.putProperty("requestCounter", requestCounter.get()); state.putProperty("responseCounter", responseCounter.get()); response.setState(state); context.replyWith(response); } else { requestCounter.incrementAndGet(); super.onInbound(context); } }
@SuppressWarnings("deprecation") protected void afterEnd(Map flags, Task<?> task) { activeTaskCount.decrementAndGet(); incompleteTaskCount.decrementAndGet(); if (log.isTraceEnabled()) log.trace(this + " afterEnd, task: " + task); ExecutionUtils.invoke(flags.get("newTaskEndCallback"), task); List l = (List) flags.get("tagLinkedPreprocessors"); Collections.reverse(l); for (Object li : l) { TaskPreprocessor t = (TaskPreprocessor) li; t.onEnd(flags, task); } PerThreadCurrentTaskHolder.perThreadCurrentTask.remove(); ((BasicTask) task).endTimeUtc = System.currentTimeMillis(); // clear thread _after_ endTime set, so we won't get a null thread when there is no end-time if (RENAME_THREADS) { String newThreadName = "brooklyn-" + LanguageUtils.newUid(); ((BasicTask) task).thread.setName(newThreadName); } ((BasicTask) task).thread = null; synchronized (task) { task.notifyAll(); } ExpirationPolicy expirationPolicy = (ExpirationPolicy) flags.get("expirationPolicy"); if (expirationPolicy == null) expirationPolicy = ExpirationPolicy.IMMEDIATE; if (expirationPolicy == ExpirationPolicy.IMMEDIATE) { for (Object t : ((BasicTask) task).tags) { getMutableTasksWithTag(t).remove(task); } } }
@Test public void shouldEvalScriptWithMapBindingsAndLanguageThenConsume() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .addEngineSettings( "nashorn", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyMap()) .create(); final Map<String, Object> b = new HashMap<>(); b.put("x", 1); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger result = new AtomicInteger(0); assertEquals( 2.0, gremlinExecutor .eval( "1+x", "nashorn", b, r -> { result.set(((Double) r).intValue() * 2); latch.countDown(); }) .get()); latch.await(); assertEquals(4, result.get()); gremlinExecutor.close(); }
public E take() throws InterruptedException { Node<E> x; final AtomicInteger count = this.count; final ReentrantLock takeLock = this.takeLock; takeLock.lockInterruptibly(); try { try { while (count.get() == 0) notEmpty.await(); } catch (InterruptedException ie) { notEmpty.signal(); // propagate to a non-interrupted thread throw ie; } x = extract(); if (count.getAndDecrement() > 1) notEmpty.signal(); } finally { takeLock.unlock(); } E result = x.item; // temporary clearence x.item = null; x.next = null; return result; }
@Test public void shouldNotExhaustThreads() throws Exception { final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2, testingThreadFactory); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .executorService(executorService) .scheduledExecutorService(executorService) .create(); final AtomicInteger count = new AtomicInteger(0); assertTrue( IntStream.range(0, 1000) .mapToObj(i -> gremlinExecutor.eval("1+1")) .allMatch( f -> { try { return (Integer) f.get() == 2; } catch (Exception ex) { throw new RuntimeException(ex); } finally { count.incrementAndGet(); } })); assertEquals(1000, count.intValue()); executorService.shutdown(); executorService.awaitTermination(30000, TimeUnit.MILLISECONDS); }
/** Returns the current number of objects, using its own transactions. */ private int getObjectCount() throws Exception { final AtomicInteger countRef = new AtomicInteger(0); final AtomicReference<BigInteger> lastRef = new AtomicReference<BigInteger>(); final AtomicBoolean done = new AtomicBoolean(false); while (!done.get()) { txnScheduler.runTask( new TestTask( new AbstractKernelRunnable() { public void run() { BigInteger last = lastRef.get(); int count; for (count = 0; count < 50; count++) { BigInteger next = dataService.nextObjectId(last); if (next == null) { done.set(true); } last = next; } countRef.addAndGet(count); lastRef.set(last); } }), taskOwner); } return countRef.get(); }
@Test public void testBaseMetaChange() throws Exception { startEngine(); m_curator .setData() .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(100L)); int retries = 50; int i = 0; while (m_baseMetaChangeCount.get() != 1 && i++ < retries) { TimeUnit.MILLISECONDS.sleep(100); } assertEquals(1, m_baseMetaChangeCount.get()); m_curator .setData() .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(200L)); i = 0; while (m_baseMetaChangeCount.get() != 2 && i++ < retries) { TimeUnit.MILLISECONDS.sleep(100); } assertEquals(2, m_baseMetaChangeCount.get()); }
@Override public void releaseClient(HClient client) throws HectorException { if (cassandraHost.getMaxActive() == 0) { client.close(); } boolean open = client.isOpen(); if (open) { if (active.get()) { addClientToPoolGently(client); } else { log.info( "Open client {} released to in-active pool for host {}. Closing.", client, cassandraHost); client.close(); } } else { try { addClientToPoolGently(createClient()); } catch (HectorTransportException e) { // if unable to open client then don't add one back to the pool log.error("Transport exception in re-opening client in release on {}", getName()); } } realActiveClientsCount.decrementAndGet(); activeClientsCount.decrementAndGet(); if (log.isTraceEnabled()) { log.trace("Status of releaseClient {} to queue: {}", client.toString(), open); } }
private Ref readRef(String name, RefList<Ref> packed) throws IOException { final RefList<LooseRef> curList = looseRefs.get(); final int idx = curList.find(name); if (0 <= idx) { final LooseRef o = curList.get(idx); final LooseRef n = scanRef(o, name); if (n == null) { if (looseRefs.compareAndSet(curList, curList.remove(idx))) modCnt.incrementAndGet(); return packed.get(name); } if (o == n) return n; if (looseRefs.compareAndSet(curList, curList.set(idx, n))) modCnt.incrementAndGet(); return n; } final LooseRef n = scanRef(null, name); if (n == null) return packed.get(name); // check whether the found new ref is the an additional ref. These refs // should not go into looseRefs for (int i = 0; i < additionalRefsNames.length; i++) if (name.equals(additionalRefsNames[i])) return n; if (looseRefs.compareAndSet(curList, curList.add(idx, n))) modCnt.incrementAndGet(); return n; }
public int sendAlarm(final AlarmInfo alarmInfo) { AlarmType type = alarmInfo.type; String id = alarmInfo.getId(); String extraInfo = alarmInfo.getExtraInfo(); if (terminationToken.isToShutdown()) { // 记录告警信息 System.err.println("rejected alarm:" + id + "," + extraInfo); return -1; } int duplicateSubmissionCount = 0; try { AtomicInteger prevSubmittedCounter; prevSubmittedCounter = submittedAlarmRegistry.putIfAbsent( type.toString() + ':' + id + '@' + extraInfo, new AtomicInteger(0)); if (null == prevSubmittedCounter) { terminationToken.reservations.incrementAndGet(); alarmQueue.put(alarmInfo); } else { // 故障未恢复,不用重复发送告警信息给服务器,故仅增加计数 duplicateSubmissionCount = prevSubmittedCounter.incrementAndGet(); } } catch (Throwable t) { t.printStackTrace(); } return duplicateSubmissionCount; }
@Test(timeout = 2000) public void testMultiTake() { final AtomicInteger count = new AtomicInteger(); Observable.create( new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> s) { for (int i = 0; !s.isUnsubscribed(); i++) { System.out.println("Emit: " + i); count.incrementAndGet(); s.onNext(i); } } }) .take(100) .take(1) .toBlocking() .forEach( new Action1<Integer>() { @Override public void call(Integer t1) { System.out.println("Receive: " + t1); } }); assertEquals(1, count.get()); }
private SliderRow forgeSliderRow(Slider slider) { String startLabel = slider.getStartLabel(); TextElement startLabelEl = uifactory.addTextElement( "start.label." + count.incrementAndGet(), "start.label", 256, startLabel, flc); startLabelEl.setDomReplacementWrapperRequired(false); String endLabel = slider.getEndLabel(); TextElement endLabelEl = uifactory.addTextElement( "end.label." + count.incrementAndGet(), "end.label", 256, endLabel, flc); endLabelEl.setDomReplacementWrapperRequired(false); SliderRow row = new SliderRow(slider, startLabelEl, endLabelEl); if (!restrictedEdit) { FormLink deleteButton = uifactory.addFormLink( "del." + count.incrementAndGet(), "delete_slider", "", null, flc, Link.BUTTON | Link.NONTRANSLATED); deleteButton.setDomReplacementWrapperRequired(false); deleteButton.setIconLeftCSS("o_icon o_icon-lg o_icon_delete_item"); deleteButton.setUserObject(row); row.setDeleteButton(deleteButton); flc.contextPut("deleteButtons", Boolean.TRUE); } return row; }
@Override public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { try { HttpServletResponse hrsp = (HttpServletResponse) rsp; if (maxConnections > 0) { if (active.getAndIncrement() > maxConnections) { String msg = maxConnectionMessage; if (msg == null) msg = "Too many simultaneous requests (this is a small server, after all, this is not a commercial service)"; hrsp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg); return; } } Coordination c = coordinator.begin("osgi.enroute.webrequest." + active.incrementAndGet(), 0); try { chain.doFilter(req, rsp); c.end(); } catch (Throwable t) { c.fail(t); throw t; } } finally { active.decrementAndGet(); } }