Example usage for java.util.concurrent.atomic AtomicReference AtomicReference

List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference AtomicReference.

Prototype

public AtomicReference() 

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@Test
public void testPair() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    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/* w w  w.j av a  2  s .c om*/
        public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) {

            this.stompSession = stompSession;
            this.stompSession.subscribe("/user/queue/device", null);

            try {
                PairMessage pair = new PairMessage();
                Device d = new Device();
                d.setUuid(UUID.randomUUID());
                pair.setDevice(d);
                pair.setType(PairMessage.Types.exit);
                pair.setGeo(new float[] { lat, lon });
                pair.setPoint(new int[] { 0, 0 });
                pair.setVector(new float[] { 1, 1 });

                stompSession.send("/app/pair", pair);
            } 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("devices").assertValueIsArray(json);
                new JsonPathExpectationsHelper("type").assertValue(json, "pair");
            } 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("Pair response not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }

}

From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java

private Map<Segment, Long> acquireSegment(long timeLag) throws ReinitializationRequiredException {
    AtomicReference<Map<Segment, Long>> result = new AtomicReference<>();
    AtomicBoolean reinitRequired = new AtomicBoolean(false);
    sync.updateState(state -> {/*from   w  w  w  . ja v  a2 s.  c om*/
        if (!state.isReaderOnline(readerId)) {
            reinitRequired.set(true);
            return null;
        }
        int toAcquire = calculateNumSegmentsToAcquire(state);
        if (toAcquire == 0) {
            result.set(Collections.emptyMap());
            return null;
        }
        Map<Segment, Long> unassignedSegments = state.getUnassignedSegments();
        Map<Segment, Long> acquired = new HashMap<>(toAcquire);
        List<ReaderGroupStateUpdate> updates = new ArrayList<>(toAcquire);
        Iterator<Entry<Segment, Long>> iter = unassignedSegments.entrySet().iterator();
        for (int i = 0; i < toAcquire; i++) {
            assert iter.hasNext();
            Entry<Segment, Long> segment = iter.next();
            acquired.put(segment.getKey(), segment.getValue());
            updates.add(new AcquireSegment(readerId, segment.getKey()));
        }
        updates.add(new UpdateDistanceToTail(readerId, timeLag));
        result.set(acquired);
        return updates;
    });
    if (reinitRequired.get()) {
        throw new ReinitializationRequiredException();
    }
    acquireTimer.reset(calculateAcquireTime(sync.getState()));
    return result.get();
}

From source file:org.appverse.web.framework.backend.frontfacade.websocket.IntegrationWebsocketTest.java

@Test
public void executeTrade() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    StompSessionHandler handler = new AbstractTestSessionHandler(failure) {

        @Override/*from  w  w  w  .j  av a2s.c o m*/
        public void afterConnected(final StompSession session, StompHeaders connectedHeaders) {
            session.subscribe("/user/queue/position-updates", new StompFrameHandler() {
                @Override
                public Type getPayloadType(StompHeaders headers) {
                    return PortfolioPosition.class;
                }

                @Override
                public void handleFrame(StompHeaders headers, Object payload) {
                    PortfolioPosition position = (PortfolioPosition) payload;
                    logger.debug("Got " + position);
                    try {
                        assertEquals(75, position.getShares());
                        assertEquals("Dell Inc.", position.getCompany());
                    } catch (Throwable t) {
                        failure.set(t);
                    } finally {
                        session.disconnect();
                        latch.countDown();
                    }
                }
            });

            try {
                Trade trade = new Trade();
                trade.setAction(Trade.TradeAction.Buy);
                trade.setTicker("DELL");
                trade.setShares(25);
                session.send("/app/trade", trade);
            } catch (Throwable t) {
                failure.set(t);
                latch.countDown();
            }
        }
    };
    //test websocket
    WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());
    stompClient.connect("ws://localhost:{port}/services/websocket/standard", headers, handler, port);

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Trade confirmation not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }
    //test sockJs
    stompClient = new WebSocketStompClient(sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());
    stompClient.connect("http://localhost:{port}/services/websocket/sockJs", headers, handler, port);

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Trade confirmation not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }

}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void absoluteRedirect() throws Exception {
    int code = 200;
    statusCode.set(code);//from www .j av  a 2s. c om
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.incrementAndGet(code);
    expected.addAndGet(302, 3);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/absoluteRedirect")).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.assertNull(throwable.get());
    assertEquals(expected, statusCounts);
}

From source file:org.elasticsearch.xpack.test.rest.XPackRestIT.java

/**
 * Executes an API call using the admin context, waiting for it to succeed.
 *///from   w w w. j a  va  2s .  co  m
private void awaitCallApi(String apiName, Map<String, String> params, List<Map<String, Object>> bodies,
        CheckedFunction<ClientYamlTestResponse, Boolean, IOException> success, Supplier<String> error)
        throws Exception {

    AtomicReference<IOException> exceptionHolder = new AtomicReference<>();
    awaitBusy(() -> {
        try {
            ClientYamlTestResponse response = callApi(apiName, params, bodies, getApiCallHeaders());
            if (response.getStatusCode() == HttpStatus.SC_OK) {
                exceptionHolder.set(null);
                return success.apply(response);
            }
            return false;
        } catch (IOException e) {
            exceptionHolder.set(e);
        }
        return false;
    });

    IOException exception = exceptionHolder.get();
    if (exception != null) {
        throw new IllegalStateException(error.get(), exception);
    }
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();/*  www  .ja v  a 2 s . co  m*/
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/foo");
        client.create().forPath("/test/bar");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch addedLatch = new CountDownLatch(2);
        final PathChildrenCache cache = new PathChildrenCache(client, "/test", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    if (event.getData().getPath().equals("/test/test")) {
                        addedLatch.countDown();
                    }
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
                    if (event.getData().getPath().equals("/test/snafu")) {
                        addedLatch.countDown();
                    }
                }
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();
        ExecutorService service = Executors.newSingleThreadExecutor();
        final AtomicReference<String> deletedPath = new AtomicReference<String>();
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                cache.rebuildTestExchanger.exchange(new Object());

                // simulate another process adding a node while we're rebuilding
                client.create().forPath("/test/test");

                List<ChildData> currentData = cache.getCurrentData();
                Assert.assertTrue(currentData.size() > 0);

                // simulate another process removing a node while we're rebuilding
                client.delete().forPath(currentData.get(0).getPath());
                deletedPath.set(currentData.get(0).getPath());

                cache.rebuildTestExchanger.exchange(new Object());

                ChildData childData = null;
                while (childData == null) {
                    childData = cache.getCurrentData("/test/snafu");
                    Thread.sleep(1000);
                }
                Assert.assertEquals(childData.getData(), "original".getBytes());
                client.setData().forPath("/test/snafu", "grilled".getBytes());

                cache.rebuildTestExchanger.exchange(new Object());

                return null;
            }
        });
        cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        future.get();

        Assert.assertTrue(addedLatch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData("/test/test"));
        Assert.assertNull(cache.getCurrentData(deletedPath.get()));
        Assert.assertEquals(cache.getCurrentData("/test/snafu").getData(), "grilled".getBytes());

        cache.close();
    } finally {
        client.close();
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

private boolean isExcluded(final String localItem, final boolean isFolder, final String startLocalItem) {
    if (ignoreFile != null) {
        if (ignoreFile.getFullPath().equalsIgnoreCase(localItem)) {
            return true;
        }/*  w ww  . ja  va 2 s  . c om*/
        final AtomicReference<String> innerAppliedExclusion = new AtomicReference<String>();
        final Boolean isExcluded = ignoreFile.isExcluded(localItem, isFolder, startLocalItem,
                innerAppliedExclusion);
        if (isExcluded != null) {
            return isExcluded.booleanValue();
        }
    }
    return false;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.localworkspace.BaselineFolder.java

/**
 * Given the root baseline folder and a baseline file GUID, calculates the
 * path that this baseline file GUID would have in that root folder, without
 * the extension (.rw or .gz)./*from   w ww .j a  v  a  2  s.com*/
 *
 * Example values for baselineFolderRootPath: @"D:\workspace\$tf" -- from
 * the instance method GetPathFromGuid immediately above and
 *
 * "C:\ProgramData\TFS\Offline\[guid]\ws1;[domain/user]
 *
 *
 * @param baselineFolderRootPath
 *        Root folder of the baseline folder structure
 * @param baselineFileGuid
 *        Baseline file GUID whose path should be computed
 * @return
 */
public static String getPathFromGUID(final String baselineFolderRootPath, final byte[] baselineFileGuid) {
    checkForValidBaselineFileGUID(baselineFileGuid);

    final AtomicReference<String> outIndividualBaselineFolder = new AtomicReference<String>();

    return getPathFromGUID(baselineFolderRootPath, baselineFileGuid, outIndividualBaselineFolder);
}

From source file:com.kinglcc.spring.jms.core.converter.Jackson2JmsMessageConverter.java

private boolean canSerialize(Object payload) {
    if (!jackson23Available || !LOGGER.isWarnEnabled()) {
        return this.objectMapper.canSerialize(payload.getClass());
    }//from  ww w . jav  a  2 s. c o  m
    AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    if (this.objectMapper.canSerialize(payload.getClass(), causeRef)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        String msg = "Failed to evaluate serialization for type [" + payload.getClass() + "]";
        if (LOGGER.isDebugEnabled()) {
            LOGGER.warn(msg, cause);
        } else {
            LOGGER.warn(msg + ": " + cause);
        }
    }
    return false;
}

From source file:TestFuseDFS.java

/**
 * Test concurrent creation and access of the mount
 *//*from w w w  .  ja  va 2 s  . c om*/
@Test
public void testMultipleThreads() throws IOException {
    ArrayList<Thread> threads = new ArrayList<Thread>();
    final AtomicReference<String> errorMessage = new AtomicReference<String>();

    for (int i = 0; i < 10; i++) {
        Thread t = new Thread() {
            public void run() {
                try {
                    File d = new File(mountPoint, "dir" + getId());
                    execWaitRet("mkdir " + d.getAbsolutePath());
                    for (int j = 0; j < 10; j++) {
                        File f = new File(d, "file" + j);
                        final String contents = "thread " + getId() + " " + j;
                        createFile(f, contents);
                    }
                    for (int j = 0; j < 10; j++) {
                        File f = new File(d, "file" + j);
                        execWaitRet("cat " + f.getAbsolutePath());
                        execWaitRet("rm " + f.getAbsolutePath());
                    }
                    execWaitRet("rmdir " + d.getAbsolutePath());
                } catch (IOException ie) {
                    errorMessage.set(String.format("Exception %s", StringUtils.stringifyException(ie)));
                }
            }
        };
        t.start();
        threads.add(t);
    }

    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException ie) {
            fail("Thread interrupted: " + ie.getMessage());
        }
    }

    assertNull(errorMessage.get(), errorMessage.get());
}