List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference
public AtomicReference()
From source file:com.android.ide.common.process.MtlProcessExecutor.java
private static ListenableFuture<Integer> grabProcessOutput(@NonNull final Process process, @NonNull final ProcessOutput output) { final SettableFuture<Integer> result = SettableFuture.create(); final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>(); /*//from w w w . j a v a 2 s .c om * It looks like on windows process#waitFor() can return before the thread have filled the * arrays, so we wait for both threads and the process itself. * * To make sure everything is complete before setting the future, the thread handling * "out" will wait for all its input to be read, will wait for the "err" thread to finish * and will wait for the process to finish. Only after all three are done will it set * the future and terminate. * * This means that the future will be set while the "out" thread is still running, but * no output is pending and the process has already finished. */ final Thread threadErr = new Thread("stderr") { @Override public void run() { InputStream stderr = process.getErrorStream(); OutputStream stream = output.getErrorOutput(); try { ByteStreams.copy(stderr, stream); stream.flush(); } catch (IOException e) { exceptionHolder.compareAndSet(null, e); } } }; Thread threadOut = new Thread("stdout") { @Override public void run() { InputStream stdout = process.getInputStream(); OutputStream stream = output.getStandardOutput(); try { ByteStreams.copy(stdout, stream); stream.flush(); } catch (Exception e) { exceptionHolder.compareAndSet(null, e); } try { threadErr.join(); int processResult = process.waitFor(); if (exceptionHolder.get() != null) { result.setException(exceptionHolder.get()); } result.set(processResult); output.close(); } catch (Exception e) { result.setException(e); } } }; threadErr.start(); threadOut.start(); return result; }
From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java
private String getBuildResponseRelativePath() { final String buildFileLocation = buildDefinition.getConfigurationFolderPath(); final AtomicReference<String> path = new AtomicReference<String>(); if (GitProperties.parseGitItemUrl(buildFileLocation, null, null, null, path)) { return path.get() + GitProperties.PathSeparator + BuildConstants.RESPONSE_FILE_NAME; }//from www . j a v a 2 s .com return null; }
From source file:org.elasticsearch.smoketest.SmokeTestWatcherWithSecurityIT.java
private ObjectPath getWatchHistoryEntry(String watchId, String state) throws Exception { final AtomicReference<ObjectPath> objectPathReference = new AtomicReference<>(); assertBusy(() -> {/*from ww w .ja v a 2s . c om*/ client().performRequest("POST", ".watcher-history-*/_refresh"); try (XContentBuilder builder = jsonBuilder()) { builder.startObject(); builder.startObject("query").startObject("bool").startArray("must"); builder.startObject().startObject("term").startObject("watch_id").field("value", watchId) .endObject().endObject().endObject(); if (Strings.isNullOrEmpty(state) == false) { builder.startObject().startObject("term").startObject("state").field("value", state).endObject() .endObject().endObject(); } builder.endArray().endObject().endObject(); builder.startArray("sort").startObject().startObject("trigger_event.triggered_time") .field("order", "desc").endObject().endObject().endArray(); builder.endObject(); StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON); Response response = client().performRequest("POST", ".watcher-history-*/_search", Collections.emptyMap(), entity); ObjectPath objectPath = ObjectPath.createFromResponse(response); int totalHits = objectPath.evaluate("hits.total"); assertThat(totalHits, is(greaterThanOrEqualTo(1))); String watchid = objectPath.evaluate("hits.hits.0._source.watch_id"); assertThat(watchid, is(watchId)); objectPathReference.set(objectPath); } }); return objectPathReference.get(); }
From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java
private MapValue removeInternal(String key, Optional<byte[]> value, Optional<MapValue> tombstone) { checkState(!closed, destroyedMessage); checkNotNull(key, ERROR_NULL_KEY);//from ww w .j av a 2 s. co m checkNotNull(value, ERROR_NULL_VALUE); tombstone.ifPresent(v -> checkState(v.isTombstone())); counter.incrementCount(); AtomicBoolean updated = new AtomicBoolean(false); AtomicReference<MapValue> previousValue = new AtomicReference<>(); items.compute(key, (k, existing) -> { boolean valueMatches = true; if (value.isPresent() && existing != null && existing.isAlive()) { valueMatches = Arrays.equals(value.get(), existing.get()); } if (existing == null) { log.trace("ECMap Remove: Existing value for key {} is already null", k); } if (valueMatches) { if (existing == null) { updated.set(tombstone.isPresent()); } else { updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing)); } } if (updated.get()) { previousValue.set(existing); return tombstone.orElse(null); } else { return existing; } }); return previousValue.get(); }
From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java
@Test public void testDevices() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> failure = new AtomicReference<>(); URI uri = new URI("ws://localhost:" + port + "/composite"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); stompClient.connect(new StompMessageHandler() { private StompSession stompSession; @Override/*from www . j av a2 s .c o m*/ public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) { this.stompSession = stompSession; String topicUuid = simulateJoinEvent(); // Call again to get a second device in the session simulateJoinEvent(); this.stompSession.subscribe("/user/queue/device", null); this.stompSession.subscribe(String.format("/topic/%s", topicUuid), null); try { // send a message to the devices endpoint HashMap<String, Object> devices = new HashMap<String, Object>(); devices.put("type", "devices"); this.stompSession.send(String.format("/app/%s", topicUuid), devices); } catch (Throwable t) { failure.set(t); latch.countDown(); } } @Override public void handleMessage(Message<byte[]> message) { try { String json = parseMessageJson(message); new JsonPathExpectationsHelper("devices").exists(json); new JsonPathExpectationsHelper("type").exists(json); new JsonPathExpectationsHelper("type").assertValue(json, "devices"); new JsonPathExpectationsHelper("serverTime").exists(json); } catch (Throwable t) { failure.set(t); } finally { this.stompSession.disconnect(); latch.countDown(); } } @Override public void handleError(Message<byte[]> message) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload()); logger.error(error); failure.set(new Exception(error)); } @Override public void handleReceipt(String receiptId) { } @Override public void afterDisconnected() { } }); if (!latch.await(10, TimeUnit.SECONDS)) { fail("Devices response not received"); } else if (failure.get() != null) { throw new AssertionError("", failure.get()); } }
From source file:com.netflix.iep.http.RxHttpTest.java
@Test public void readTimeout() throws Exception { //set(client + ".niws.client.ReadTimeout", "100"); int code = 200; statusCode.set(code);/*from w ww.j a va 2 s. com*/ AtomicIntegerArray expected = copy(statusCounts); expected.addAndGet(code, 3); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> throwable = new AtomicReference<>(); rxHttp.get(uri("/readTimeout")).subscribe(Actions.empty(), new Action1<Throwable>() { @Override public void call(Throwable t) { throwable.set(t); latch.countDown(); } }, new Action0() { @Override public void call() { latch.countDown(); } }); latch.await(); Assert.assertTrue(throwable.get() instanceof ReadTimeoutException); assertEquals(expected, statusCounts); }
From source file:info.archinnov.achilles.test.integration.tests.AsyncQueryIT.java
@Test public void should_return_raw_entities_for_raw_typed_query_async() throws Exception { Counter counter1 = CounterBuilder.incr(15L); CompleteBean paul = builder().randomId().name("Paul").age(35L).addFriends("foo", "bar") .addFollowers("George", "Jack").addPreference(1, "FR").addPreference(2, "Paris") .addPreference(3, "75014").version(counter1).buid(); Counter counter2 = CounterBuilder.incr(17L); CompleteBean john = builder().randomId().name("John").age(34L).addFriends("qux", "twix") .addFollowers("Isaac", "Lara").addPreference(1, "US").addPreference(2, "NewYork").version(counter2) .buid();/*from w w w . j a v a 2 s . c o m*/ asyncManager.insert(paul).getImmediately(); asyncManager.insert(john).getImmediately(); final CountDownLatch latch = new CountDownLatch(2); final AtomicReference<Object> successSpy1 = new AtomicReference<>(); final AtomicReference<Object> successSpy2 = new AtomicReference<>(); FutureCallback<Object> successCallBack1 = new FutureCallback<Object>() { @Override public void onSuccess(Object result) { successSpy1.getAndSet(result); latch.countDown(); } @Override public void onFailure(Throwable t) { latch.countDown(); } }; FutureCallback<Object> successCallBack2 = new FutureCallback<Object>() { @Override public void onSuccess(Object result) { successSpy2.getAndSet(result); latch.countDown(); } @Override public void onFailure(Throwable t) { latch.countDown(); } }; final RegularStatement selectStar = select().from("CompleteBean").where(eq("id", bindMarker("id"))); final AchillesFuture<CompleteBean> futurePaul = asyncManager .rawTypedQuery(CompleteBean.class, selectStar, paul.getId()).getFirst(successCallBack1); final AchillesFuture<CompleteBean> futureJohn = asyncManager .rawTypedQuery(CompleteBean.class, selectStar, john.getId()).getFirst(successCallBack2); latch.await(); CompleteBean foundPaul = futurePaul.get(); assertThat(foundPaul.getName()).isEqualTo(paul.getName()); assertThat(foundPaul.getAge()).isEqualTo(paul.getAge()); assertThat(foundPaul.getFriends()).containsAll(paul.getFriends()); assertThat(foundPaul.getFollowers()).containsAll(paul.getFollowers()); assertThat(foundPaul.getPreferences().get(1)).isEqualTo("FR"); assertThat(foundPaul.getPreferences().get(2)).isEqualTo("Paris"); assertThat(foundPaul.getPreferences().get(3)).isEqualTo("75014"); assertThat(foundPaul.getVersion()).isNull(); CompleteBean foundJohn = futureJohn.get(); assertThat(foundJohn.getName()).isEqualTo(john.getName()); assertThat(foundJohn.getAge()).isEqualTo(john.getAge()); assertThat(foundJohn.getFriends()).containsAll(john.getFriends()); assertThat(foundJohn.getFollowers()).containsAll(john.getFollowers()); assertThat(foundJohn.getPreferences().get(1)).isEqualTo("US"); assertThat(foundJohn.getPreferences().get(2)).isEqualTo("NewYork"); assertThat(foundJohn.getVersion()).isNull(); assertThat(successSpy1.get()).isNotNull().isInstanceOf(CompleteBean.class).isNotInstanceOf(Factory.class); assertThat(successSpy2.get()).isNotNull().isInstanceOf(CompleteBean.class).isNotInstanceOf(Factory.class); }
From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java
@Test public void shouldFireKeepAlive() throws Exception { final AtomicInteger keepAliveEventCounter = new AtomicInteger(); final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference(); ViewHandler testHandler = new ViewHandler(endpoint, responseRingBuffer, queue, false) { @Override/*from www.j a v a2s . c om*/ public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); ctxRef.compareAndSet(null, ctx); } @Override protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) { assertEquals(1, keepAliveEventCounter.incrementAndGet()); } @Override protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) { assertEquals(2, keepAliveEventCounter.incrementAndGet()); } }; EmbeddedChannel channel = new EmbeddedChannel(testHandler); //test idle event triggers a view keepAlive request and hook is called testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT); assertEquals(1, keepAliveEventCounter.get()); assertTrue(queue.peek() instanceof ViewHandler.KeepAliveRequest); ViewHandler.KeepAliveRequest keepAliveRequest = (ViewHandler.KeepAliveRequest) queue.peek(); //test responding to the request with http response is interpreted into a KeepAliveResponse and hook is called HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channel.writeInbound(response); ViewHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable() .cast(ViewHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single(); assertEquals(2, keepAliveEventCounter.get()); assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status()); }
From source file:de.codesourcery.jasm16.parser.InstructionNodeTest.java
public void testParseNestedImmediateExpression() throws Exception { final String source = "SET I, 4+5*3"; final ICompilationUnit unit = CompilationUnit.createInstance("string input", source); final IParseContext context = createParseContext(source); final ASTNode result = new InstructionNode().parse(context); assertFalse(getErrors(source, result), result.hasErrors()); assertEquals(InstructionNode.class, result.getClass()); final InstructionNode instruction = (InstructionNode) result; final AtomicReference<byte[]> objcode = new AtomicReference<byte[]>(); final IObjectCodeWriter writer = new IObjectCodeWriter() { @Override//from ww w.jav a 2s. c o m public void close() throws IOException { } @Override public void writeObjectCode(byte[] data, int offset, int length) throws IOException { objcode.set(ArrayUtils.subarray(data, offset, offset + length)); } @Override public void writeObjectCode(byte[] data) throws IOException { writeObjectCode(data, 0, data.length); } @Override public void deleteOutput() throws IOException { // TODO Auto-generated method stub } @Override public Address getCurrentWriteOffset() { return Address.ZERO; } @Override public Address getFirstWriteOffset() { return Address.ZERO; } @Override public void advanceToWriteOffset(Address offset) throws IOException { throw new UnsupportedOperationException("Not implemented"); } }; final ICompilationContext compContext = createCompilationContext(unit); final OperandNode operand = instruction.getOperand(1); final TermNode oldExpression = (TermNode) operand.child(0); final TermNode newExpression = oldExpression.reduce(compContext); if (newExpression != oldExpression) { operand.setChild(0, newExpression); } instruction.symbolsResolved(compContext); instruction.writeObjectCode(writer, compContext); assertNotNull(objcode.get()); assertEquals(source, toSourceCode(result, source)); }
From source file:hudson.plugins.jobConfigHistory.FileHistoryDao.java
/** * Creates a new history entry./* w ww .ja v a 2 s .c o m*/ * * @param xmlFile to save. * @param operation description * * @return timestampedDir */ File createNewHistoryEntry(final XmlFile xmlFile, final String operation) { try { final AtomicReference<Calendar> timestampHolder = new AtomicReference<Calendar>(); final File timestampedDir = getRootDir(xmlFile, timestampHolder); LOG.log(Level.FINE, "{0} on {1}", new Object[] { this, timestampedDir }); createHistoryXmlFile(timestampHolder.get(), timestampedDir, operation); assert timestampHolder.get() != null; return timestampedDir; } catch (IOException e) { // If not able to create the history entry, log, but continue without it. // A known issue is where Hudson core fails to move the folders on rename, // but continues as if it did. // Reference https://issues.jenkins-ci.org/browse/JENKINS-8318 throw new RuntimeException( "Unable to create history entry for configuration file: " + xmlFile.getFile().getAbsolutePath(), e); } }