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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.google.code.jahath.common.io.SwappableInputStreamTest.java

@Test
public void test() throws Throwable {
    final SwappableInputStream swappableInputStream = new SwappableInputStream("test");
    final CRC actualCRC = new CRC();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                actualCRC.update(swappableInputStream);
            } catch (Throwable ex) {
                thrown.set(ex);
            }/*from   w w w.  ja va2  s  .co  m*/
        }
    });
    thread.start();
    Random random = new Random();
    CRC expectedCRC = new CRC();
    for (int i = 0; i < 100; i++) {
        int len = 2048 + random.nextInt(4096);
        byte[] data = new byte[len];
        random.nextBytes(data);
        expectedCRC.update(data);
        CountingInputStream in = new CountingInputStream(new ByteArrayInputStream(data));
        swappableInputStream.swap(in);
        // Check that the stream has been consumed entirely
        Assert.assertEquals(len, in.getCount());
    }
    swappableInputStream.sendEndOfStream();
    thread.join();
    if (thrown.get() != null) {
        throw thrown.get();
    }
    Assert.assertEquals(expectedCRC.getValue(), actualCRC.getValue());
}

From source file:org.hawkular.metrics.dropwizard.HawkularReporterITest.java

@Test
public void shouldReportGauge() throws InterruptedException, IOException {
    String metricName = randomName();
    HawkularReporter reporter = HawkularReporter.builder(registry, defaultTenant).uri(BASE_URI).build();

    final AtomicReference<Double> gauge = new AtomicReference<>(10d);
    registry.register(metricName, (Gauge<Double>) gauge::get);
    reporter.report();//  w w  w .  j a  v  a2  s.com
    gauge.set(7.1);
    Thread.sleep(50);
    reporter.report();
    gauge.set(13.4);
    Thread.sleep(50);
    reporter.report();

    HawkularHttpResponse response = defaultClient.readMetric("gauges", metricName);

    assertThat(response.getResponseCode()).isEqualTo(200);
    JSONArray result = new JSONArray(response.getContent());
    assertThat(result).extracting(doubleExtractor).usingElementComparator(new DoubleComparator(0.001))
            .containsExactly(13.4, 7.1, 10d);
}

From source file:my.adam.smo.client.Client.java

public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) {
    return new BlockingRpcChannel() {
        private int countDownCallTimesToRelease = 1;
        private RpcChannel rpc = connect(sa);

        @Override/*from w  ww .ja  v a2  s. c om*/
        public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller,
                Message request, Message responsePrototype) throws ServiceException {
            StopWatch stopWatch = new StopWatch("callBlockingMethod");
            stopWatch.start();

            final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease);

            final AtomicReference<Message> result = new AtomicReference<Message>();

            RpcCallback<Message> done = new RpcCallback<Message>() {
                @Override
                public void run(Message parameter) {
                    result.set(parameter);
                    callbackLatch.countDown();
                }
            };

            rpc.callMethod(method, controller, request, responsePrototype, done);
            try {
                boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout,
                        TimeUnit.SECONDS);
                if (!succeededBeforeTimeout) {
                    throw new ServiceException(
                            "blocking method timeout reached for method:" + method.getFullName());
                }
            } catch (InterruptedException e) {
                getLogger().error("call failed", e);
                stopWatch.stop();
            }

            stopWatch.stop();
            getLogger().trace(stopWatch.shortSummary());

            return result.get();
        }
    };
}

From source file:org.elasticsearch.xpack.security.audit.index.AuditTrailTests.java

private Collection<Map<String, Object>> waitForAuditEvents() throws InterruptedException {
    waitForAuditTrailToBeWritten();/*from   w  w w.  j ava2  s . com*/
    final AtomicReference<Collection<Map<String, Object>>> eventsRef = new AtomicReference<>();
    awaitBusy(() -> {
        try {
            final Collection<Map<String, Object>> events = getAuditEvents();
            eventsRef.set(events);
            return events.size() > 0;
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    });

    return eventsRef.get();
}

From source file:org.apache.hadoop.hbase.client.TestAsyncRegionLocator.java

@Test
public void testNoCompletionException() {
    // make sure that we do not get CompletionException
    SLEEP_MS = 0;//  w  w  w .ja va2s.  c om
    AtomicReference<Throwable> errorHolder = new AtomicReference<>();
    try {
        LOCATOR.getRegionLocation(TableName.valueOf("NotExist"), EMPTY_START_ROW, RegionLocateType.CURRENT,
                TimeUnit.SECONDS.toNanos(1)).whenComplete((r, e) -> errorHolder.set(e)).join();
        fail();
    } catch (CompletionException e) {
        // join will return a CompletionException, which is OK
        assertThat(e.getCause(), instanceOf(TableNotFoundException.class));
    }
    // but we need to make sure that we do not get a CompletionException in the callback
    assertThat(errorHolder.get(), instanceOf(TableNotFoundException.class));
}

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

@Test
public void testCallback() {
    String json = "[{\"value\":5,\"if\":{\"d1\":[\"v1\",\"v2\"]}, \"comment\": \"some comment\"},{\"value\":10,\"if\":{\"d1\":[\"v3\"],\"d2\":[\"x1\"]}, \"runtimeEval\": true},{\"value\":2}]";
    ConfigurationManager.getConfigInstance().setProperty("d1", "v2");
    final AtomicReference<Integer> ref = new AtomicReference<Integer>();
    DynamicContextualProperty<Integer> prop = new DynamicContextualProperty<Integer>("propWithCallback", 0) {
        @Override/*from  w ww  .  ja  v a 2s.  co m*/
        protected void propertyChanged(Integer newVal) {
            ref.set(newVal);
        }
    };
    assertEquals(0, prop.getValue().intValue());
    ConfigurationManager.getConfigInstance().setProperty("propWithCallback", json);
    assertEquals(5, ref.get().intValue());
    assertEquals(5, prop.getValue().intValue());
    assertEquals("some comment", prop.values.get(0).getComment());
    assertTrue(prop.values.get(1).isRuntimeEval());
    assertFalse(prop.values.get(0).isRuntimeEval());
    // set the property as a single value integer
    ConfigurationManager.getConfigInstance().setProperty("propWithCallback", "7");
    assertEquals(7, ref.get().intValue());
    assertEquals(7, prop.getValue().intValue());
}

From source file:org.eclipse.mylyn.commons.repositories.http.tests.CommonHttpClientTest.java

@Test
public void testHttpContextPerThread() throws Exception {
    RepositoryLocation location = new RepositoryLocation("http://mylyn.org/");
    final CommonHttpClient client = new CommonHttpClient(location);
    final AtomicReference<HttpContext> otherThreadContext = new AtomicReference<HttpContext>();
    Thread t = new Thread() {
        @Override//from  www.  j  av  a2s.  c  o  m
        public void run() {
            otherThreadContext.set(client.getContext());
        };
    };
    t.start();
    t.join();
    assertNotNull(otherThreadContext.get());
    assertNotNull(client.getContext());
    assertFalse(otherThreadContext.get() == client.getContext());
}

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestExecutionContextTests.java

public void testHeadersSupportStashedValueReplacement() throws IOException {
    final AtomicReference<Map<String, String>> headersRef = new AtomicReference<>();
    final ClientYamlTestExecutionContext context = new ClientYamlTestExecutionContext(null, randomBoolean()) {
        @Override//from w  w w.  j  a v  a  2  s.  c o m
        ClientYamlTestResponse callApiInternal(String apiName, Map<String, String> params, HttpEntity entity,
                Map<String, String> headers) {
            headersRef.set(headers);
            return null;
        }
    };
    final Map<String, String> headers = new HashMap<>();
    headers.put("foo", "$bar");
    headers.put("foo1", "baz ${c}");

    context.stash().stashValue("bar", "foo2");
    context.stash().stashValue("c", "bar1");

    assertNull(headersRef.get());
    context.callApi("test", Collections.emptyMap(), Collections.emptyList(), headers);
    assertNotNull(headersRef.get());
    assertNotEquals(headers, headersRef.get());

    assertEquals("foo2", headersRef.get().get("foo"));
    assertEquals("baz bar1", headersRef.get().get("foo1"));
}

From source file:de.sainth.recipe.backend.db.repositories.BasicUnitRepository.java

public BasicUnit save(BasicUnit basicUnit) {
    AtomicReference<BasicUnit> bu = new AtomicReference<>();
    create.transaction(configuration -> {
        using(configuration).insertInto(BASIC_UNITS, BASIC_UNITS.SHORTNAME, BASIC_UNITS.LONGNAME)
                .values(basicUnit.getShortname(), basicUnit.getLongname()).onConflict().doUpdate()
                .set(BASIC_UNITS.LONGNAME, basicUnit.getLongname()).execute();
        bu.set(using(configuration).selectFrom(BASIC_UNITS)
                .where(BASIC_UNITS.SHORTNAME.eq(basicUnit.getShortname())).fetchOneInto(BasicUnit.class));
    });/* ww  w  .  j  av a 2s.  c o  m*/

    return bu.get();
}

From source file:com.vmware.admiral.adapter.docker.service.SystemImageRetrievalManagerTest.java

@Test
public void testGetFromClassPath() throws Throwable {
    Path testXenonImagesPath = Files.createTempDirectory("test-xenon-images");

    HostInitCommonServiceConfig.startServices(host);
    waitForServiceAvailability(ConfigurationFactoryService.SELF_LINK);
    waitForServiceAvailability(UriUtils.buildUriPath(UriUtils
            .buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE)));

    // Set expected configuration
    ConfigurationState config = new ConfigurationState();
    config.documentSelfLink = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK,
            FileUtil.USER_RESOURCES_PATH_VARIABLE);
    config.key = FileUtil.USER_RESOURCES_PATH_VARIABLE;
    config.value = testXenonImagesPath.toAbsolutePath().toString();

    doPost(config, ConfigurationFactoryService.SELF_LINK);

    File imageDir = new File(UriUtils.buildUriPath(testXenonImagesPath.toString(),
            SystemImageRetrievalManager.SYSTEM_IMAGES_PATH));
    imageDir.mkdir();// w  w  w . j  a  va 2 s .  co  m

    byte[] content = IOUtils
            .toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEST_IMAGE));

    AdapterRequest req = new AdapterRequest();
    req.resourceReference = host.getUri();

    AtomicReference<byte[]> retrievedImageRef = new AtomicReference<>();

    TestContext ctx = testCreate(1);
    retrievalManager.retrieveAgentImage(TEST_IMAGE, req, (image) -> {
        retrievedImageRef.set(image);
        ctx.completeIteration();
    });

    ctx.await();

    byte[] image = retrievedImageRef.get();
    Assert.assertEquals("Unexpected content", new String(content), new String(image));
}