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.microsoft.tfs.client.common.ui.wizard.common.WizardServerSelectionPage.java

private List<TFSConnection> getConfigurationServers(final List<Account> accounts,
        final AtomicReference<JwtCredentials> vstsCredentialsHolder,
        final Action<DeviceFlowResponse> deviceFlowCallback) {
    final List<TFSConnection> configurationServers = new ArrayList<TFSConnection>(100);

    final JwtCredentials vstsCredentials = vstsCredentialsHolder.get();
    for (final Account account : accounts) {
        log.debug("Account name = " + account.getAccountName()); //$NON-NLS-1$
        log.debug("Account URI  = " + account.getAccountUri()); //$NON-NLS-1$

        final String accountURI = "https://" + account.getAccountName() + ".visualstudio.com"; //$NON-NLS-1$ //$NON-NLS-2$

        try {/*from w w w .  j a  v  a 2 s .co  m*/
            final URI uri = URIUtils.newURI(accountURI);
            final TFSConnection configurationServer = openAccount(uri,
                    CredentialsHelper.getOAuthCredentials(uri, vstsCredentials, deviceFlowCallback));
            if (configurationServer != null) {
                configurationServers.add(configurationServer);
            }
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    return configurationServers;
}

From source file:info.archinnov.achilles.it.TestEntityWithStaticColumn.java

@Test
public void should_insert_static_if_not_exist() throws Exception {
    //Given/*from w  w w  .j  a v a  2s.  c o  m*/
    final AtomicReference<LWTResult> lwtResultRef = new AtomicReference<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final EntityWithStaticColumn entity = new EntityWithStaticColumn(id, null, "static_val", null);

    manager.crud().insertStatic(entity).ifNotExists().execute();

    //When
    manager.crud().insertStatic(entity).ifNotExists().withLwtResultListener(lwtResultRef::set).execute();

    //Then
    assertThat(lwtResultRef.get()).isNotNull();
    assertThat(lwtResultRef.get().currentValues().<String>getTyped("static_col")).isEqualTo("static_val");
}

From source file:com.netflix.discovery.shared.Applications.java

/**
 * Gets the list of <em>instances</em> associated to a virtual host name.
 *
 * @param virtualHostName//from ww w .  ja  v  a 2 s . c om
 *            the virtual hostname for which the instances need to be
 *            returned.
 * @return list of <em>instances</em>.
 */
public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) {
    AtomicReference<List<InstanceInfo>> ref = this.shuffleVirtualHostNameMap
            .get(virtualHostName.toUpperCase(Locale.ROOT));
    if (ref == null || ref.get() == null) {
        return new ArrayList<InstanceInfo>();
    } else {
        return ref.get();
    }
}

From source file:org.apache.batchee.cli.command.SocketCommand.java

protected void sendCommand() {
    if (adminSocket < 0) {
        throw new BatchContainerRuntimeException("specify -socket to be able to run this command");
    }/*w  ww  .ja  v a2  s. c  o  m*/

    Socket socket = null;
    try {
        socket = new Socket("localhost", adminSocket);
        socket.setSoTimeout(timeout);

        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Integer> answer = new AtomicReference<Integer>();
        new AnswerThread(socket, answer, latch).start();

        final OutputStream outputStream = socket.getOutputStream();
        outputStream.write(command().getBytes());
        outputStream.flush();
        socket.shutdownOutput();

        try {
            latch.await(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            info("no answer after " + timeout + "ms");
            return;
        }
        if (answer.get() != 0) {
            info("unexpected answer: " + answer.get());
        }
    } catch (final IOException e) {
        throw new BatchContainerRuntimeException(e);
    } finally {
        IOUtils.closeQuietly(socket);
    }
}

From source file:com.netflix.discovery.shared.Applications.java

/**
 * Gets the list of secure <em>instances</em> associated to a virtual host
 * name./*from  www .jav  a 2  s.  c o  m*/
 *
 * @param secureVirtualHostName
 *            the virtual hostname for which the secure instances need to be
 *            returned.
 * @return list of <em>instances</em>.
 */
public List<InstanceInfo> getInstancesBySecureVirtualHostName(String secureVirtualHostName) {
    AtomicReference<List<InstanceInfo>> ref = this.shuffledSecureVirtualHostNameMap
            .get(secureVirtualHostName.toUpperCase(Locale.ROOT));
    if (ref == null || ref.get() == null) {
        return new ArrayList<InstanceInfo>();
    } else {
        return ref.get();
    }
}

From source file:de.hybris.platform.test.HJMPTest.java

@Test
public void testHiddenPKLookupWithRetry() {
    final PK nonExistingProductPK = PK.createFixedPK(Constants.TC.Product, System.nanoTime());

    final long TIMEOUT = 30 * 1000;

    final Object token = HJMPUtils.enablePKLookupRetry(TIMEOUT, 500);
    try {//from  w  w  w  .  ja v a  2 s. c  om
        // start lookup in own thread -> must wait since PK doesnt exist yet
        final AtomicReference<Boolean> success = startPKLookupInOtherThread(nonExistingProductPK);

        // wait for 5 seconds to allow a decent amount of turns
        Thread.sleep(5 * 1000);
        assertNull("Result available before end of lookup retry period", success.get()); // still no result

        // now create product with exactly that pk -> now lookup should succeed eventually
        final Product product = ProductManager.getInstance().createProduct(null, nonExistingProductPK, "PPP");
        assertTrue(product.isAlive());
        final PK createdPK = product.getPK();
        assertEquals(createdPK, nonExistingProductPK); // sanity check

        // wait for lookup result for 10 seconds 
        final long maxWait = System.currentTimeMillis() + TIMEOUT;
        while (success.get() == null && System.currentTimeMillis() < maxWait) {
            Thread.sleep(500);
        }
        assertEquals("Wrong retry lookup result", Boolean.TRUE, success.get());
    } catch (final Exception e) {
        fail(e.getMessage());
    } finally {
        HJMPUtils.restorPKLookupRetry(token);
    }
}

From source file:com.netflix.config.ConcurrentMapConfigurationTest.java

@Test
public void testListeners() {
    ConcurrentMapConfiguration conf = new ConcurrentMapConfiguration();
    final AtomicReference<ConfigurationEvent> eventRef = new AtomicReference<ConfigurationEvent>();
    conf.addConfigurationListener(new ConfigurationListener() {
        @Override/*from  w  w  w  .ja v  a  2s.  com*/
        public void configurationChanged(ConfigurationEvent arg0) {
            eventRef.set(arg0);
        }

    });
    conf.addProperty("key", "1");
    assertEquals(1, conf.getInt("key"));
    ConfigurationEvent event = eventRef.get();
    assertEquals("key", event.getPropertyName());
    assertEquals("1", event.getPropertyValue());
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_ADD_PROPERTY, event.getType());
    conf.setProperty("key", "2");
    event = eventRef.get();
    assertEquals("key", event.getPropertyName());
    assertEquals("2", event.getPropertyValue());
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_SET_PROPERTY, event.getType());
    conf.clearProperty("key");
    event = eventRef.get();
    assertEquals("key", event.getPropertyName());
    assertNull(event.getPropertyValue());
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_CLEAR_PROPERTY, event.getType());
    conf.clear();
    assertFalse(conf.getKeys().hasNext());
    event = eventRef.get();
    assertTrue(conf == event.getSource());
    assertEquals(AbstractConfiguration.EVENT_CLEAR, event.getType());
}

From source file:org.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldListEmptyMetricTypesWhenChunksAreIncomplete() {
    // Data & mocks
    Metric<String> m1 = new Metric<>("inventory.123.mt.m1", null, 7, MetricType.STRING, null);
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.just(m1));
    DataPoint<String> tempDataPoint = buildMetricTypeDatapoint(currentTime - 500, "metricType1",
            "metric type 1");
    DataPoint<String> dataPoint = new DataPoint<>(tempDataPoint.getTimestamp(), tempDataPoint.getValue(),
            ImmutableMap.<String, String>builder().put("chunks", "3").put("size", "1000").build());
    when(metricsService.findStringData(m1.getMetricId(), 0, currentTime, false, 0, Order.DESC))
            .thenReturn(Observable.just(dataPoint));

    // Test & assertions
    AtomicReference<Throwable> refException = new AtomicReference<>();
    InventoryHelper.listMetricTypes(metricsService, "tenant", "feed", currentTime).toList().subscribe(a -> {
    }, refException::set);/*from  w  w w. j  av a  2 s .  c  o m*/
    Assert.assertEquals(InvalidInventoryChunksException.class, refException.get().getCause().getClass());
    Assert.assertTrue("Unexpected message: " + refException.get().getCause().getMessage(),
            refException.get().getCause().getMessage()
                    .contains("Inventory sanity check failure: 3 chunks expected, only 1 are available"));
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphoreCluster.java

@Test
public void testKilledServerWithEnsembleProvider() throws Exception {
    final int CLIENT_QTY = 10;
    final Timing timing = new Timing();
    final String PATH = "/foo/bar/lock";

    ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY);
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
    TestingCluster cluster = new TestingCluster(3);
    try {// w w  w .  java 2s  .  c  o  m
        cluster.start();

        final AtomicReference<String> connectionString = new AtomicReference<String>(
                cluster.getConnectString());
        final EnsembleProvider provider = new EnsembleProvider() {
            @Override
            public void start() throws Exception {
            }

            @Override
            public String getConnectionString() {
                return connectionString.get();
            }

            @Override
            public void close() throws IOException {
            }
        };

        final Semaphore acquiredSemaphore = new Semaphore(0);
        final AtomicInteger acquireCount = new AtomicInteger(0);
        final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY);
        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.builder().ensembleProvider(provider)
                            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
                            .retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
                    try {
                        final Semaphore suspendedSemaphore = new Semaphore(0);
                        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
                            @Override
                            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                                if ((newState == ConnectionState.SUSPENDED)
                                        || (newState == ConnectionState.LOST)) {
                                    suspendedLatch.countDown();
                                    suspendedSemaphore.release();
                                }
                            }
                        });

                        client.start();

                        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1);

                        while (!Thread.currentThread().isInterrupted()) {
                            Lease lease = null;
                            try {
                                lease = semaphore.acquire();
                                acquiredSemaphore.release();
                                acquireCount.incrementAndGet();
                                suspendedSemaphore.acquire();
                            } catch (Exception e) {
                                // just retry
                            } finally {
                                if (lease != null) {
                                    acquireCount.decrementAndGet();
                                    IOUtils.closeQuietly(lease);
                                }
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        Assert.assertEquals(1, acquireCount.get());

        cluster.close();
        timing.awaitLatch(suspendedLatch);
        timing.forWaiting().sleepABit();
        Assert.assertEquals(0, acquireCount.get());

        cluster = new TestingCluster(3);
        cluster.start();

        connectionString.set(cluster.getConnectString());
        timing.forWaiting().sleepABit();

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        timing.forWaiting().sleepABit();
        Assert.assertEquals(1, acquireCount.get());
    } finally {
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdownNow();
        IOUtils.closeQuietly(cluster);
    }
}

From source file:org.hawkular.listener.cache.InventoryHelperTest.java

@Test
public void shouldFailOnListMetricTypesWhenChunksAreInvalid() {
    // Data & mocks
    Metric<String> m1 = new Metric<>("inventory.123.mt.m1", null, 7, MetricType.STRING, null);
    long currentTime = System.currentTimeMillis();
    when(metricsService.findMetricsWithFilters(anyString(), anyObject(), anyString()))
            .thenAnswer(invocationOnMock -> Observable.just(m1));
    DataPoint<String> tempDataPoint = buildMetricTypeDatapoint(currentTime - 500, "metricType1",
            "metric type 1");
    DataPoint<String> dataPoint = new DataPoint<>(tempDataPoint.getTimestamp(), tempDataPoint.getValue(),
            ImmutableMap.<String, String>builder().put("chunks", "3").put("size", "1000").build());
    when(metricsService.findStringData(m1.getMetricId(), 0, currentTime, false, 0, Order.DESC))
            .thenReturn(Observable.just(dataPoint,
                    buildMetricTypeDatapoint(currentTime - 501, "metricType1", "metric type 1"),
                    buildMetricTypeDatapoint(currentTime - 800, "metricType1", "metric type 1")));

    // Test & assertions
    AtomicReference<Throwable> refException = new AtomicReference<>();
    InventoryHelper.listMetricTypes(metricsService, "tenant", "feed", currentTime).toList().subscribe(a -> {
    }, refException::set);/*from ww w.  j  av  a  2  s  . co  m*/
    Assert.assertEquals(InvalidInventoryChunksException.class, refException.get().getCause().getClass());
    Assert.assertTrue("Unexpected message: " + refException.get().getCause().getMessage(), refException.get()
            .getCause().getMessage().contains("Inventory sanity check failure: chunk n2 timestamp is"));
}