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:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManagerSeparateThread() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");
    try {/*from  w w  w . j a v a  2 s. co  m*/

        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);

        instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(
                new LinkedList<String>());
        Future<Object> future1 = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return instanceManager.doWithInstance(pid1, new IInstanceCallback() {
                    public IExecutorResult execute(IInstance instance) throws Exception {
                        log.info("locking one");
                        Thread.sleep(2000);
                        results.get().add("one");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        Thread.sleep(100);
        assertNotNull(future1.get());
    } finally {
        context.destroy();
    }
}

From source file:com.opinionlab.woa.WallOfAwesome.java

private static SockJSHandler makeEventStream(Vertx vertx) {
    final SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000);
    final SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);

    sockJSHandler.socketHandler(socket -> {
        final AtomicInteger openCount = new AtomicInteger();
        final AtomicBoolean running = new AtomicBoolean(true);
        LOGGER.info(format("[OPEN] Sockets: %d", openCount.incrementAndGet()));

        socket.endHandler(aVoid -> {/*from   ww w. ja  v a 2s .c  o m*/
            running.set(false);
            LOGGER.info(format("[CLOSE] Sockets: %d", openCount.decrementAndGet()));
        });

        socket.handler(buffer -> {
            String command = buffer.toString();
            if ("purge".equals(command)) {
                EXECUTOR.execute(() -> {
                    try {
                        AwesomeImap.purge(s -> socket.write(buffer(objectToJson(
                                HashTreePMap.empty().plus("deleted", true).plus("id", s.getId()), NO_TYPES))));
                    } catch (NoSuchProviderException e) {
                        LOGGER.error("Could not purge messages", e);
                    }
                });
            } else {
                LOGGER.error(format("Unknown command: %s", command));
            }
        });

        try {
            final AtomicReference<Date> latestDate = new AtomicReference<>(new Date(0));

            Consumer<Awesome> publishAwesome = awesome -> {
                socket.write(buffer(objectToJson(awesome, NO_TYPES)));

                final Date receivedDate = awesome.getReceivedDate();
                if (latestDate.get().before(receivedDate)) {
                    latestDate.set(receivedDate);
                }
            };
            AwesomeImap.fetchAwesome().forEach(publishAwesome);

            EXECUTOR.execute(() -> {
                LOGGER.info("Polling started.");
                try {
                    while (running.get()) {
                        AwesomeImap.fetchAwesomeSince(latestDate.get()).forEach(publishAwesome);
                        Thread.sleep(1000);
                    }
                } catch (Throwable t) {
                    running.set(false);
                    socket.close();
                    LOGGER.error("Polling ended ABNORMALLY", t);
                } finally {
                    LOGGER.info("Polling ended normally.");
                }
            });
        } catch (MessagingException e) {
            LOGGER.error("Unable to fetch messages.", e);
        }
    });
    return sockJSHandler;
}

From source file:org.workspace7.moviestore.controller.ShoppingCartController.java

/**
 * @param modelAndView//from  www . j  a v a2  s . c  om
 * @param session
 * @param response
 * @return
 */
@GetMapping("/cart/show")
public ModelAndView showCart(ModelAndView modelAndView, HttpSession session, HttpServletResponse response) {

    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");

    modelAndView.addObject("hostname", hostname);

    MovieCart movieCart = (MovieCart) session.getAttribute(SESSION_ATTR_MOVIE_CART);

    log.info("Showing Cart {}", movieCart);

    if (movieCart != null) {

        modelAndView.addObject("movieCart", movieCart);
        AtomicReference<Double> cartTotal = new AtomicReference<>(0.0);
        Map<String, Integer> movieItems = movieCart.getMovieItems();
        List<MovieCartItem> cartMovies = movieCart.getMovieItems().keySet().stream().map(movieId -> {
            Movie movie = movieDBHelper.query(movieId);
            int quantity = movieItems.get(movieId);
            double total = quantity * movie.getPrice();
            cartTotal.updateAndGet(aDouble -> aDouble + total);
            log.info("Movie:{} total for {} items is {}", movie, quantity, total);
            return MovieCartItem.builder().movie(movie).quantity(quantity).total(total).build();
        }).collect(Collectors.toList());
        modelAndView.addObject("cartItems", cartMovies);
        modelAndView.addObject("cartCount", cartMovies.size());
        modelAndView.addObject("cartTotal",
                "" + DecimalFormat.getCurrencyInstance(Locale.US).format(cartTotal.get()));
        modelAndView.setViewName("cart");

    } else {
        modelAndView.setViewName("redirect:/");
    }
    return modelAndView;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.BaselineFileDownloadOutput.java

/**
 * {@inheritDoc}/*from ww  w  .j  av a 2  s . c  o  m*/
 */
@Override
public synchronized OutputStream getOutputStream() throws IOException {
    if (outputStream == null) {
        final String contentType = getActualContentType();
        Check.notNull(contentType, "Cannot open output stream until actual content type is set"); //$NON-NLS-1$

        String path = baselineFileNoSuffix.getAbsolutePath();
        if (contentType.equals(DownloadContentTypes.APPLICATION_GZIP)) {
            path = path + BaselineFolder.getGzipExtension();
        } else if (contentType.equals(DownloadContentTypes.APPLICATION_OCTET_STREAM)) {
            path = path + BaselineFolder.getRawExtension();
        } else {
            throw new VersionControlException(MessageFormat.format(
                    Messages.getString("VersionControlClient.UnsupportedContentTypeFormat"), //$NON-NLS-1$
                    contentType));

        }

        final AtomicBoolean tempCreated = new AtomicBoolean();

        final AtomicReference<String> pathReference = new AtomicReference<String>(path);
        outputStream = BaselineFolderCollection.createFile(pathReference, true, null /* ignored */,
                tempCreated);
        path = pathReference.get();

        outputStreamFile = new File(path);
        tempFileCreatedInsteadOfBaseline = tempCreated.get();
    }

    return outputStream;
}

From source file:io.spring.initializr.metadata.Link.java

/**
 * Expand the link using the specified parameters.
 * @param parameters the parameters value
 * @return an URI where all variables have been expanded
 *//*www .j  a va  2  s .c  om*/
public URI expand(Map<String, String> parameters) {
    AtomicReference<String> result = new AtomicReference<>(href);
    templateVariables.forEach(var -> {
        Object value = parameters.get(var);
        if (value == null) {
            throw new IllegalArgumentException(
                    "Could not expand " + href + ", missing value for '" + var + "'");
        }
        result.set(result.get().replace("{" + var + "}", value.toString()));
    });
    try {
        return new URI(result.get());
    } catch (URISyntaxException e) {
        throw new IllegalStateException("Invalid URL", e);
    }
}

From source file:com.codeabovelab.dm.cluman.job.AbstractJobInstance.java

public AbstractJobInstance(Config config) {
    Assert.notNull(config.parameters, "parameters is null");
    Assert.notNull(config.job, "job is null");
    Assert.notNull(config.jobsManager, "jobsManager is null");
    Assert.notNull(config.info, "info is null");
    this.jobContext = new JobContext(this, config.parameters);
    this.infoRef = new AtomicReference<>(config.info);
    this.manager = config.jobsManager;
    // create wait future with stub
    this.atEndFuture = SettableFuture.create();
    this.job = config.job;
    this.authentication = config.authentication;
    this.watcher = config.watcher;
    this.cancelFuture = ListenableFutureTask.create(this::innerCancel);
    this.startFuture = ListenableFutureTask.create(this::innerStart);
}

From source file:com.amazon.alexa.avs.NotificationManager.java

NotificationManager(NotificationIndicator indicator, SimpleAudioPlayer audioPlayer, BasicHttpClient httpClient,
        FileDataStore<NotificationsStatePayload> dataStore) {
    this.notificationIndicator = indicator;
    this.player = audioPlayer;
    this.assets = Collections.synchronizedMap(new HashMap<String, File>());
    this.indicatorExecutor = Executors.newSingleThreadExecutor();
    this.assetDownloader = Executors.newCachedThreadPool();
    this.allowPersistentIndicator = new AtomicBoolean(true);
    this.httpClient = httpClient;
    this.isSetIndicatorPersisted = new AtomicBoolean(false);
    this.indicatorStatus = Status.NONE;
    this.dataStore = dataStore;
    this.indicatorFutures = Collections.synchronizedSet(new HashSet<Future<?>>());
    this.activeAudioAsset = new AtomicReference<String>("");
    this.resLoader = Thread.currentThread().getContextClassLoader();
}

From source file:com.bigdata.rdf.sparql.ast.service.ServiceRegistry.java

protected ServiceRegistry() {

    services = new ConcurrentHashMap<URI, ServiceFactory>();

    customServices = new CopyOnWriteArrayList<CustomServiceFactory>();

    aliases = new ConcurrentHashMap<URI, URI>();

    defaultServiceFactoryRef = new AtomicReference<ServiceFactory>(
            new RemoteServiceFactoryImpl(SPARQLVersion.SPARQL_11));

    // Add the Bigdata search service.
    add(BDS.SEARCH, new SearchServiceFactory());

    // Add the Geospatial search service.
    add(GeoSpatial.SEARCH, new GeoSpatialServiceFactory());

    // Add the external Solr search service
    add(FTS.SEARCH, new FulltextSearchServiceFactory());

    // Add the Bigdata search in search service.
    add(BDS.SEARCH_IN_SEARCH, new SearchInSearchServiceFactory());

    // Add the sample index service.
    add(SampleServiceFactory.SERVICE_KEY, new SampleServiceFactory());

    // Add the slice index service.
    add(SliceServiceFactory.SERVICE_KEY, new SliceServiceFactory());

    // Add the values service.
    add(ValuesServiceFactory.SERVICE_KEY, new ValuesServiceFactory());

    if (QueryHints.DEFAULT_DESCRIBE_CACHE) {

        add(new URIImpl(BD.NAMESPACE + "describe"), new DescribeServiceFactory());

    }/*from  w ww.j  a  va  2 s . c om*/

    if (true) {

        /**
         * @see <a
         *      href="https://sourceforge.net/apps/trac/bigdata/ticket/607">
         *      HISTORY SERVICE </a>
         */
        add(new URIImpl(BD.NAMESPACE + "history"), new HistoryServiceFactory());

        /**
         * Replacing with a history service using RDR instead of a custom
         * index.
         */
        add(new URIImpl(BD.NAMESPACE + "rdrhistory"), new RDRHistoryServiceFactory());

    }

    // The Gather-Apply-Scatter RDF Graph Mining service.
    add(GASService.Options.SERVICE_KEY, new GASService());

}

From source file:com.microsoft.tfs.core.TFSConfigurationServer.java

/**
 * The most complete way of creating a {@link TFSConfigurationServer}. A
 * {@link URI}, {@link Credentials} and a {@link ConnectionAdvisor} are
 * specified./*  www  . ja v a  2  s. c om*/
 *
 * @param serverURI
 *        the {@link URI} to connect to (must not be <code>null</code>)
 * @param credentials
 *        the {@link Credentials} to connect with
 * @param advisor
 *        the {@link ConnectionAdvisor} to use (must not be
 *        <code>null</code>)
 */
public TFSConfigurationServer(final URI serverURI, final Credentials credentials,
        final ConnectionAdvisor advisor) {
    this(serverURI, new AtomicReference<Credentials>(credentials), advisor);
}

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

@Test
public void testChanging() throws Exception {
    TestingServer secondServer = new TestingServer();
    try {/*from  w ww . j  a v a2 s . c  o m*/
        String mainConnectionString = "count=1&port=" + server.getPort() + "&server0=localhost";
        String secondConnectionString = "count=1&port=" + secondServer.getPort() + "&server0=localhost";

        final Semaphore semaphore = new Semaphore(0);
        final AtomicReference<String> connectionString = new AtomicReference<String>(mainConnectionString);
        Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000,
                dummyConnectionStringProvider);
        ExhibitorRestClient mockRestClient = new ExhibitorRestClient() {
            @Override
            public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception {
                semaphore.release();
                return connectionString.get();
            }
        };
        ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo",
                10, new RetryOneTime(1));
        provider.pollForInitialEnsemble();

        Timing timing = new Timing().multiple(4);
        final CuratorZookeeperClient client = new CuratorZookeeperClient(provider, timing.session(),
                timing.connection(), null, new RetryOneTime(2));
        client.start();
        try {
            RetryLoop.callWithRetry(client, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    client.getZooKeeper().create("/test", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
                            CreateMode.PERSISTENT);
                    return null;
                }
            });

            connectionString.set(secondConnectionString);
            semaphore.drainPermits();
            semaphore.acquire();

            server.stop(); // create situation where the current zookeeper gets a sys-disconnected

            Stat stat = RetryLoop.callWithRetry(client, new Callable<Stat>() {
                @Override
                public Stat call() throws Exception {
                    return client.getZooKeeper().exists("/test", false);
                }
            });
            Assert.assertNull(stat); // it's a different server so should be null
        } finally {
            client.close();
        }
    } finally {
        IOUtils.closeQuietly(secondServer);
    }
}