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

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

Introduction

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

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java

@Test
public void testRetryOnConflict() throws InterruptedException {
    final String index = "JresUpdateDocumentTest.testRetryOnConflict".toLowerCase();
    final String type = "test";
    final String id = "warzone";

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

    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {
        x.submit(new Runnable() {
            @Override//from   w ww .j  a v a  2s.c o  m
            public void run() {
                try {
                    for (int j = 0; j < numIterations; j++) {
                        JresUpdateDocument req = new JresUpdateDocument(index, type, id,
                                ImmutableMap.of("value", 0));
                        req.setRetryOnConflict(numIterations * 10);
                        jres.quest(req);
                    }
                } catch (Exception e) {
                    error.set(e.getMessage());
                }
            }
        });
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    Assert.assertNull("With so many retries, all of these should have gotten through without conflict error",
            error.get());
    jres.quest(new JresRefresh(index));
    JresGetDocumentReply getReply = jres.quest(new JresGetDocument(index, type, id));
    Map<String, Integer> doc = getReply.getSourceAsType(new TypeReference<Map<String, Integer>>() {
    });
    Assert.assertEquals("Should have been numThreads * numIterations versions committed",
            (Object) (numThreads * numIterations), getReply.getVersion());
}

From source file:io.syndesis.jsondb.impl.SqlJsonDB.java

@Override
public Set<String> fetchIdsByPropertyValue(final String collectionPath, final String property,
        final String value) {
    final String pathRegex = collectionPath + "/:[^/]+/" + property;

    final AtomicReference<Set<String>> ret = new AtomicReference<>();
    withTransaction(dbi -> {/* ww w .  ja v  a 2  s .  co  m*/
        final String query;
        if (databaseKind == DatabaseKind.PostgreSQL) {
            query = "SELECT regexp_replace(path, '(/.+/:[^/]+).*', '\\1') from jsondb where path ~ ? and value = ?";
        } else if (databaseKind == DatabaseKind.H2) {
            query = "SELECT regexp_replace(path, '(/.+/:[^/]+).*', '$1') from jsondb where path regexp ? and value = ?";
        } else {
            throw new UnsupportedOperationException(
                    "Don't know how to use regex in a query with database: " + databaseKind);
        }

        final List<String> paths = dbi.createQuery(query).bind(0, pathRegex).bind(1, value)
                .map(StringColumnMapper.INSTANCE).list();

        ret.set(new HashSet<>(paths));
    });

    return ret.get();
}

From source file:com.sm.store.client.ClusterClient.java

/**
 *
 * @param invoker//from w ww. j av a  2s.  c  o m
 * @param keys
 * @return future
 */
public Future clusterStoreProcFuture(final Invoker invoker, final List<Key> keys) {
    AtomicReference<FutureTask<List<Object>>> future = new AtomicReference<FutureTask<List<Object>>>(
            new FutureTask<List<Object>>(new Callable<List<Object>>() {
                public List<Object> call() {
                    return clusterStoreProc(invoker, keys);
                }
            }));
    futureExecutor.execute(future.get());
    return future.get();
}

From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_notify_listener_when_trying_to_insert_with_LWT_because_already_exist() throws Exception {
    //Given//from w ww .  j a  v  a  2s . com
    final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicLWTResult.compareAndSet(null, lwtResult);
        }
    };
    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM);
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("id", 10L, "[applied]", false,
            "consistency_level", EACH_QUORUM.name(), "name", "name");
    manager.insert(entityWithEnum);

    manager.insert(entityWithEnum, OptionsBuilder.ifNotExists().lwtResultListener(listener));

    final LWTResultListener.LWTResult lwtResult = atomicLWTResult.get();
    assertThat(lwtResult.operation()).isEqualTo(INSERT);
    assertThat(lwtResult.currentValues()).isEqualTo(expectedCurrentValues);
    assertThat(lwtResult.toString()).isEqualTo(
            "CAS operation INSERT cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, id=10, name=name}");
}

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

@Test
public void testDeleteThenCreate() throws Exception {
    NodeCache cache = null;//from   w w  w.  j  ava 2 s . c  o  m
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try {
        client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes());

        final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
        client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {
            @Override
            public void unhandledError(String message, Throwable e) {
                error.set(e);
            }
        });

        final Semaphore semaphore = new Semaphore(0);
        cache = new NodeCache(client, "/test/foo");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                semaphore.release();
            }
        });
        cache.start(true);

        Assert.assertEquals(cache.getCurrentData().getData(), "one".getBytes());

        client.delete().forPath("/test/foo");
        Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS));
        client.create().forPath("/test/foo", "two".getBytes());
        Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS));

        Throwable t = error.get();
        if (t != null) {
            Assert.fail("Assert", t);
        }

        Assert.assertEquals(cache.getCurrentData().getData(), "two".getBytes());

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

From source file:org.zodiark.publisher.PublisherTest.java

@Test(enabled = false)
public void startStreamingSession() throws IOException, InterruptedException {

    final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch connected = new CountDownLatch(1);
    final AtomicReference<String> uuid = new AtomicReference<>();

    // Fake Wowza Client

    wowzaClient.handler(new OnEnvelopHandler() {
        @Override/* w w  w.  j a  va 2 s. c o m*/
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case SERVER_VALIDATE_OK:
                Envelope publisherOk = Envelope
                        .newClientToServerRequest(new Message(new Path(""), e.getMessage().getData()));
                wowzaClient.send(publisherOk);
                break;
            default:
                // ERROR
            }

            connected.countDown();
            return false;
        }
    }).open();

    Envelope wowzaConnect = Envelope.newClientToServerRequest(
            new Message(new Path(WOWZA_CONNECT), mapper.writeValueAsString(new UserPassword("wowza", "bar"))));
    wowzaClient.send(wowzaConnect);
    connected.await();

    // Publisher

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope
            .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("publisherex", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
    answer.set(null);

    final CountDownLatch tlatch = new CountDownLatch(1);
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            tlatch.countDown();
            return true;
        }
    });

    Envelope startStreamingSession = Envelope
            .newClientToServerRequest(new Message(new Path(VALIDATE_PUBLISHER_STREAMING_SESSION),
                    mapper.writeValueAsString(new WowzaUUID(uuid.get()))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(startStreamingSession);

    tlatch.await();

    assertEquals("OK", answer.get().getResults());

}

From source file:org.zodiark.publisher.PublisherTest.java

@Test(enabled = false)
public void failedStreamingSession() throws IOException, InterruptedException {

    final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch connected = new CountDownLatch(1);
    final AtomicReference<String> uuid = new AtomicReference<>();

    wowzaClient.handler(new OnEnvelopHandler() {
        @Override/*from w w  w .j  a v  a  2 s  . c o m*/
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case SERVER_VALIDATE_OK:
                UUID uuid = mapper.readValue(e.getMessage().getData(), UUID.class);
                PublisherResults result = new PublisherResults("error");
                result.setUuid(uuid.getUuid());
                Envelope publisherOk = Envelope.newClientToServerRequest(new Message(
                        new Path(FAILED_PUBLISHER_STREAMING_SESSION), mapper.writeValueAsString(result)));
                wowzaClient.send(publisherOk);
                break;
            default:
                // ERROR
            }

            connected.countDown();
            return false;
        }
    }).open();

    Envelope wowzaConnect;
    wowzaConnect = Envelope.newClientToServerRequest(
            new Message(new Path(WOWZA_CONNECT), mapper.writeValueAsString(new UserPassword("wowza", "bar"))));
    wowzaClient.send(wowzaConnect);
    connected.await();

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope
            .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("publisherex", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
    answer.set(null);

    final CountDownLatch tlatch = new CountDownLatch(1);
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            tlatch.countDown();
            return true;
        }
    });

    Envelope startStreamingSession = Envelope
            .newClientToServerRequest(new Message(new Path(VALIDATE_PUBLISHER_STREAMING_SESSION),
                    mapper.writeValueAsString(new WowzaUUID(uuid.get()))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(startStreamingSession);

    tlatch.await();

    assertEquals("ERROR", answer.get().getResults());

}

From source file:com.dgtlrepublic.anitomyj.ParserNumber.java

/**
 * Match type and episode. e.g. "2x01", "S01E03", "S01-02xE001-150".
 *
 * @param word  the word/*ww  w  .j a v  a2s  . co m*/
 * @param token the token
 * @return true if the token matched
 */
public boolean matchTypeAndEpisodePattern(String word, Token token) {
    int numberBegin = ParserHelper.indexOfFirstDigit(word);
    String prefix = StringUtils.substring(word, 0, numberBegin);

    AtomicReference<ElementCategory> category = new AtomicReference<>(kElementAnimeType);
    AtomicReference<KeywordOptions> options = new AtomicReference<>();

    if (KeywordManager.getInstance().findAndSet(KeywordManager.normalzie(prefix), category, options)) {
        parser.getElements().add(new Element(kElementAnimeType, prefix));
        String number = StringUtils.substring(word, numberBegin);
        if (matchEpisodePatterns(number, token) || setEpisodeNumber(number, token, true)) {
            int foundIdx = parser.getTokens().indexOf(token);
            if (foundIdx != -1) {
                token.setContent(number);
                parser.getTokens().add(foundIdx, new Token(
                        options.get().isIdentifiable() ? kIdentifier : kUnknown, prefix, token.isEnclosed()));
            }

            return true;
        }
    }

    return false;
}

From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_notify_listener_when_trying_to_insert_with_lwt_and_ttl_because_already_exist()
        throws Exception {
    //Given/* w ww . j a  va2  s  .  com*/
    final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicLWTResult.compareAndSet(null, lwtResult);
        }
    };
    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM);
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("id", 10L, "[applied]", false,
            "consistency_level", EACH_QUORUM.name(), "name", "name");
    manager.insert(entityWithEnum);

    manager.insert(entityWithEnum, OptionsBuilder.ifNotExists().withTtl(100).lwtResultListener(listener));

    final LWTResultListener.LWTResult LWTResult = atomicLWTResult.get();
    assertThat(LWTResult.operation()).isEqualTo(INSERT);
    assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues);
    assertThat(LWTResult.toString()).isEqualTo(
            "CAS operation INSERT cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, id=10, name=name}");
}

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

@Test
public void connectTimeout() throws Exception {
    // Pick a free port with no server running
    ServerSocket ss = new ServerSocket(0);
    int serverPort = ss.getLocalPort();
    ss.close();/*from   ww  w. ja  v a  2  s.  c o  m*/

    set(client + ".niws.client.ConnectTimeout", "100");
    int code = 200;
    statusCode.set(code);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get("niws://test/http://localhost:" + serverPort + "/empty").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 ConnectException);
}