List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
From source file:com.raphfrk.craftproxyclient.gui.GUIManager.java
public static JSONObject getNewLoginDetails() { final AtomicReference<LoginDialog> login = new AtomicReference<LoginDialog>(); Runnable r = (new Runnable() { public void run() { login.set(new LoginDialog(CraftProxyClient.getGUI())); login.get().setVisible(true); login.get().dispose();/*from w w w . ja v a2s . c o m*/ } }); if (SwingUtilities.isEventDispatchThread()) { r.run(); } else { try { SwingUtilities.invokeAndWait(r); } catch (InvocationTargetException | InterruptedException e) { return null; } } return AuthManager.authAccessToken(login.get().getEmail(), login.get().getPassword()); }
From source file:org.elasticsearch.client.HeapBufferedAsyncResponseConsumerTests.java
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override/*from w w w . j a v a 2 s .c o m*/ public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch (ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
From source file:Main.java
/** * Runs arbitrary code in the Event Dispatch Thread. * <p>/*w w w .ja v a2s . c o m*/ * The first operation performed by this method is fetching the {@code Object} to return. If {@code supplier} is not {@code null}, its {@code get()} method will be called to fetch the {@code Object}. But if {@code supplier} is {@code null}, or it * produces a {@code null} "value" from its {@code get()} method, then {@code defaultObject}, which may also be {@code null}, will be used instead. * <p> * The second operation performed by this method is handling the {@code Object} to return. So if neither {@code consumer} nor the fetched {@code Object} are {@code null}, the fetched {@code Object} will be handed to {@code consumer}. * <p> * Returns the fetched {@code Object}, which may be {@code null}. * * @param <T> the type of the returned result * @param supplier the {@code Supplier}, which may be {@code null} * @param consumer the {@code Consumer}, which may be {@code null} * @param defaultObject the default {@code Object}, which may be {@code null} * @return the fetched {@code Object}, which may be {@code null} */ public static <T> T runInEDT(final Supplier<T> supplier, final Consumer<T> consumer, final T defaultObject) { final AtomicReference<T> atomicReference = new AtomicReference<>(); if (supplier != null) { runInEDT(() -> atomicReference.set(supplier.get())); } if (defaultObject != null) { atomicReference.compareAndSet(null, defaultObject); } if (atomicReference.get() != null && consumer != null) { runInEDT(() -> consumer.accept(atomicReference.get())); } return atomicReference.get(); }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.mock.TestUtils.java
/** * Waits until the build is started, or the timeout has expired. * * @param reference the reference of future build to start. * @param timeoutMs the maximum time in ms to wait for the build to start. * @return the build that started./*from w w w. j av a2 s . co m*/ */ public static Run waitForBuildToStart(AtomicReference<Run> reference, int timeoutMs) { long startTime = System.currentTimeMillis(); while (reference.get() == null) { if (System.currentTimeMillis() - startTime >= timeoutMs) { throw new RuntimeException("Timeout!"); } try { Thread.sleep(SLEEP_DURATION); } catch (InterruptedException e) { System.err.println("Interrupted while waiting!"); } } return reference.get(); }
From source file:org.apache.accumulo.server.util.RemoveEntriesForMissingFiles.java
private static int checkTable(ClientContext context, String table, Range range, boolean fix) throws Exception { @SuppressWarnings({ "rawtypes" }) Map cache = new LRUMap(100000); Set<Path> processing = new HashSet<Path>(); ExecutorService threadPool = Executors.newFixedThreadPool(16); System.out.printf("Scanning : %s %s\n", table, range); VolumeManager fs = VolumeManagerImpl.get(); Connector connector = context.getConnector(); Scanner metadata = connector.createScanner(table, Authorizations.EMPTY); metadata.setRange(range);/* ww w. j av a 2 s .co m*/ metadata.fetchColumnFamily(DataFileColumnFamily.NAME); int count = 0; AtomicInteger missing = new AtomicInteger(0); AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>(null); BatchWriter writer = null; if (fix) writer = connector.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig()); for (Entry<Key, Value> entry : metadata) { if (exceptionRef.get() != null) break; count++; Key key = entry.getKey(); Path map = fs.getFullPath(key); synchronized (processing) { while (processing.size() >= 64 || processing.contains(map)) processing.wait(); if (cache.get(map) != null) { continue; } processing.add(map); } threadPool.submit(new CheckFileTask(cache, fs, missing, writer, key, map, processing, exceptionRef)); } threadPool.shutdown(); synchronized (processing) { while (processing.size() > 0) processing.wait(); } if (exceptionRef.get() != null) throw new AccumuloException(exceptionRef.get()); if (writer != null && missing.get() > 0) writer.close(); System.out.printf("Scan finished, %d files of %d missing\n\n", missing.get(), count); return missing.get(); }
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 -> {// w w w . ja v a 2 s.com 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:Main.java
public static void runInThread(final Runnable runnable) throws Throwable { final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Runnable exceptionGuard = new Runnable() { public void run() { try { runnable.run();//from www .jav a 2 s. com } catch (Throwable throwable) { exception.set(throwable); } } }; Thread thread = new Thread(exceptionGuard); thread.setDaemon(true); thread.start(); thread.join(); if (exception.get() != null) { throw exception.get(); } }
From source file:com.github.anba.test262.environment.Environments.java
/** * Creates a new Rhino environment// ww w.ja v a 2s .co m */ public static <T extends GlobalObject> EnvironmentProvider<T> rhino(final Configuration configuration) { final int version = configuration.getInt("rhino.version", Context.VERSION_DEFAULT); final String compiler = configuration.getString("rhino.compiler.default"); List<?> enabledFeatures = configuration.getList("rhino.features.enabled", emptyList()); List<?> disabledFeatures = configuration.getList("rhino.features.disabled", emptyList()); final Set<Integer> enabled = intoCollection(filterMap(enabledFeatures, notEmptyString, toInteger), new HashSet<Integer>()); final Set<Integer> disabled = intoCollection(filterMap(disabledFeatures, notEmptyString, toInteger), new HashSet<Integer>()); /** * Initializes the global {@link ContextFactory} according to the * supplied configuration * * @see ContextFactory#initGlobal(ContextFactory) */ final ContextFactory factory = new ContextFactory() { @Override protected boolean hasFeature(Context cx, int featureIndex) { if (enabled.contains(featureIndex)) { return true; } else if (disabled.contains(featureIndex)) { return false; } return super.hasFeature(cx, featureIndex); } @Override protected Context makeContext() { Context context = super.makeContext(); context.setLanguageVersion(version); return context; } }; EnvironmentProvider<RhinoGlobalObject> provider = new EnvironmentProvider<RhinoGlobalObject>() { @Override public RhinoEnv<RhinoGlobalObject> environment(final String testsuite, final String sourceName, final Test262Info info) { Configuration c = configuration.subset(testsuite); final boolean strictSupported = c.getBoolean("strict", false); final String encoding = c.getString("encoding", "UTF-8"); final String libpath = c.getString("lib_path"); final Context cx = factory.enterContext(); final AtomicReference<RhinoGlobalObject> $global = new AtomicReference<>(); final RhinoEnv<RhinoGlobalObject> environment = new RhinoEnv<RhinoGlobalObject>() { @Override public RhinoGlobalObject global() { return $global.get(); } @Override protected String getEvaluator() { return compiler; } @Override protected String getCharsetName() { return encoding; } @Override public void exit() { Context.exit(); } }; @SuppressWarnings({ "serial" }) final RhinoGlobalObject global = new RhinoGlobalObject() { { cx.initStandardObjects(this, false); } @Override protected boolean isStrictSupported() { return strictSupported; } @Override protected String getDescription() { return info.getDescription(); } @Override protected void failure(String message) { failWith(message, sourceName); } @Override protected void include(Path path) throws IOException { // resolve the input file against the library path Path file = Paths.get(libpath).resolve(path); InputStream source = Files.newInputStream(file); environment.eval(file.getFileName().toString(), source); } }; $global.set(global); return environment; } }; @SuppressWarnings("unchecked") EnvironmentProvider<T> p = (EnvironmentProvider<T>) provider; return p; }
From source file:io.lettuce.core.support.ConnectionPoolSupport.java
/** * Creates a new {@link GenericObjectPool} using the {@link Supplier}. * * @param connectionSupplier must not be {@literal null}. * @param config must not be {@literal null}. * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using * {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the * pool when invoking {@link StatefulConnection#close()}. * @param <T> connection type.//from w w w . j a v a 2 s . co m * @return the connection pool. */ @SuppressWarnings("unchecked") public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool( Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) { LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null"); LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null"); AtomicReference<Origin<T>> poolRef = new AtomicReference<>(); GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<T>(connectionSupplier), config) { @Override public T borrowObject() throws Exception { return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get()) : super.borrowObject(); } @Override public void returnObject(T obj) { if (wrapConnections && obj instanceof HasTargetConnection) { super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection()); return; } super.returnObject(obj); } }; poolRef.set(new ObjectPoolWrapper<>(pool)); return pool; }
From source file:io.lettuce.core.support.ConnectionPoolSupport.java
/** * Creates a new {@link SoftReferenceObjectPool} using the {@link Supplier}. * * @param connectionSupplier must not be {@literal null}. * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using * {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the * pool when invoking {@link StatefulConnection#close()}. * @param <T> connection type.//w w w.jav a 2 s . c o m * @return the connection pool. */ @SuppressWarnings("unchecked") public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool( Supplier<T> connectionSupplier, boolean wrapConnections) { LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null"); AtomicReference<Origin<T>> poolRef = new AtomicReference<>(); SoftReferenceObjectPool<T> pool = new SoftReferenceObjectPool<T>( new RedisPooledObjectFactory<>(connectionSupplier)) { @Override public T borrowObject() throws Exception { return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get()) : super.borrowObject(); } @Override public void returnObject(T obj) throws Exception { if (wrapConnections && obj instanceof HasTargetConnection) { super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection()); return; } super.returnObject(obj); } }; poolRef.set(new ObjectPoolWrapper<>(pool)); return pool; }