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(V initialValue) 

Source Link

Document

Creates a new AtomicReference with the given initial value.

Usage

From source file:com.netflix.curator.ensemble.exhibitor.TestExhibitorEnsembleProvider.java

@Test
public void testExhibitorFailures() throws Exception {
    final AtomicReference<String> backupConnectionString = new AtomicReference<String>("backup1:1");
    final AtomicReference<String> connectionString = new AtomicReference<String>(
            "count=1&port=2&server0=localhost");
    Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000,
            new Exhibitors.BackupConnectionStringProvider() {
                @Override/*from w ww. ja  va2s . c o  m*/
                public String getBackupConnectionString() {
                    return backupConnectionString.get();
                }
            });
    ExhibitorRestClient mockRestClient = new ExhibitorRestClient() {
        @Override
        public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception {
            String localConnectionString = connectionString.get();
            if (localConnectionString == null) {
                throw new IOException();
            }
            return localConnectionString;
        }
    };

    final Semaphore semaphore = new Semaphore(0);
    ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo", 10,
            new RetryOneTime(1)) {
        @Override
        protected void poll() {
            super.poll();
            semaphore.release();
        }
    };
    provider.pollForInitialEnsemble();
    try {
        provider.start();

        Assert.assertEquals(provider.getConnectionString(), "localhost:2");

        connectionString.set(null);
        semaphore.drainPermits();
        semaphore.acquire(); // wait for next poll
        Assert.assertEquals(provider.getConnectionString(), "backup1:1");

        backupConnectionString.set("backup2:2");
        semaphore.drainPermits();
        semaphore.acquire(); // wait for next poll
        Assert.assertEquals(provider.getConnectionString(), "backup2:2");

        connectionString.set("count=1&port=3&server0=localhost3");
        semaphore.drainPermits();
        semaphore.acquire(); // wait for next poll
        Assert.assertEquals(provider.getConnectionString(), "localhost3:3");
    } finally {
        IOUtils.closeQuietly(provider);
    }
}

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

@Test
public void testServerLoss() throws Exception {
    Timing timing = new Timing();

    CuratorFramework client = null;/*  w ww  . jav  a  2s.  c  om*/
    PathChildrenCache cache = null;
    TestingCluster cluster = new TestingCluster(3);
    try {
        cluster.start();

        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/test");

        cache = new PathChildrenCache(client, "/test", false);
        cache.start();

        final CountDownLatch resetLatch = new CountDownLatch(1);
        final CountDownLatch reconnectLatch = new CountDownLatch(1);
        final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>(
                new CountDownLatch(3));
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED) {
                    resetLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) {
                    reconnectLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    latch.get().countDown();
                }
            }
        });

        client.create().forPath("/test/one");
        client.create().forPath("/test/two");
        client.create().forPath("/test/three");

        Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS));

        InstanceSpec connectionInstance = cluster
                .findConnectionInstance(client.getZookeeperClient().getZooKeeper());
        cluster.killServer(connectionInstance);

        Assert.assertTrue(timing.awaitLatch(reconnectLatch));

        Assert.assertEquals(cache.getCurrentData().size(), 3);
    } finally {
        IOUtils.closeQuietly(cache);
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}

From source file:io.watchcat.node.metrics.NetworkConnections.java

public NetworkConnections() {
    command = new ShellCommand("netstat -ntu | awk 'NR>2 {sub(/:[^:]+$/, \"\"); print $5}' | sort | uniq -c");

    totalConnections = new AtomicLong(0);
    connections = new AtomicReference<LinkedList<ConnectionsData>>(new LinkedList<ConnectionsData>());
}

From source file:com.foglyn.core.FogBugzClientFactory.java

FogBugzClientFactory(HttpClient httpClient) {
    Assert.isNotNull(httpClient);/*from   w  w w  .  j ava  2 s . c  om*/

    this.httpClient = httpClient;
    this.clients = new HashMap<Pair<String, AuthenticationCredentials>, FogBugzClient>();
    this.repositoryLocationFactory = new AtomicReference<TaskRepositoryLocationFactory>(
            new TaskRepositoryLocationFactory());
}

From source file:io.watchcat.node.alerts.email.EmailAddressPoller.java

public EmailAddressPoller() {
    emailAddresses = new AtomicReference<List<String>>(new ArrayList<String>(5));
}

From source file:com.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java

@Test
public void testBasicHystrixCommand() throws Exception {

    final AtomicBoolean done = new AtomicBoolean(false);
    final AtomicReference<String> result = new AtomicReference<>(null);

    // kick off async command
    Observable<String> observable = new TestCommand().observe();

    // Sleep to test what happens if command finishes before subscription
    Thread.sleep(2000);/*  www  . ja  v a2s.  c o m*/

    // Add handler
    observable.subscribe(new Observer<String>() {
        @Override
        public void onCompleted() {
            done.set(true);
        }

        @Override
        public void onError(Throwable e) {
            result.set("error!!");
            done.set(true);
        }

        @Override
        public void onNext(String args) {
            result.set(args);
            done.set(true);
        }
    });

    // spin until done
    while (!done.get()) {
        Thread.sleep(100);
    }

    Assert.assertEquals(resultString, result.get());
}

From source file:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManager() throws Exception {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");

    final IInstanceManager instanceManager = (IInstanceManager) context.getBean("instanceManager");

    final String pid1 = instanceManager.createInstance("parentVersion", "definitionId", "test",
            IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "one");
    IInstance instance = instanceManager.getInstance(pid1);
    assertNotNull(instance);//from  w w  w.  j  a v  a  2 s. com

    instanceManager.createInstance("parentVersion", "definitionId", "test",
            IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
    final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(new LinkedList<String>());
    Object operation = instanceManager.doWithInstance(pid1, new IInstanceCallback() {
        public IExecutorResult execute(IInstance instance) throws Exception {
            log.info("locking one");
            results.get().add("one");
            return new IgnoredResult("", "", "");
        }
    });
    assertTrue(operation instanceof IIgnoredResult);
}

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 {/*from  ww w . ja  va  2s. c om*/
        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:edu.umich.robot.util.SimBattery.java

/**
 * @param mAh_max//w  w w  .j  av a2 s .co  m
 * @param doc depth of charge
 */
public SimBattery(double mAh_max, double doc) {
    if (doc > 1.0 || doc < 0.1)
        doc = 1.0;
    if (mAh_max < 0)
        mAh_max = 10000;

    this.mAh_max = mAh_max;
    this.mAh = new AtomicReference<Double>(Double.valueOf(mAh_max));
    this.mAh_min = mAh_max * (1 - doc);

    logger.trace("Battery created with max " + mAh_max + " min " + mAh_min);

    start();
}

From source file:edu.cornell.mannlib.vitro.webapp.tboxreasoner.ConfiguredReasonerListener.java

public ConfiguredReasonerListener(ReasonerConfiguration reasonerConfiguration,
        TBoxReasonerDriver reasonerDriver) {
    this.reasonerConfiguration = reasonerConfiguration;
    this.reasonerDriver = reasonerDriver;

    this.drivingPatternMap = new DrivingPatternMap(reasonerConfiguration.getInferenceDrivingPatternAllowSet());

    this.changeSet = new AtomicReference<>(new TBoxChanges());
    this.suspended = new AtomicBoolean();
}