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:objective.taskboard.it.BoardStepFragment.java

public void assertIssueList(String... expectedIssueKeyList) {
    AtomicReference<String> s = new AtomicReference<>();
    try {/*  w  w w .ja  va2  s. com*/
        waitUntil((w) -> {
            s.set(join(issueList(), "\n"));
            return s.get().equals(join(expectedIssueKeyList, "\n"));
        });
    } catch (TimeoutException e) {
        assertEquals(join(expectedIssueKeyList, "\n"), s.get());
    }
}

From source file:com.lambdaworks.redis.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./* ww  w .j a v  a 2s.co  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<ObjectPool<T>> poolRef = new AtomicReference<>();

    SoftReferenceObjectPool<T> pool = new SoftReferenceObjectPool<T>(
            new RedisPooledObjectFactory<>(connectionSupplier)) {
        @Override
        public synchronized T borrowObject() throws Exception {
            return wrapConnections ? wrapConnection(super.borrowObject(), this) : super.borrowObject();
        }

        @Override
        public synchronized void returnObject(T obj) throws Exception {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };
    poolRef.set(pool);

    return pool;
}

From source file:org.openmrs.module.drughistory.api.DrugEventServiceTest.java

/**
 * @verifies throw exception when sinceWhen is in the future
 * @see DrugEventService#generateDrugEventsFromTrigger(org.openmrs.module.drughistory.DrugEventTrigger, java.util.Date)
 *///  w w w .j  av  a  2s  .c o m
@Test
@ExpectedException(IllegalArgumentException.class)
public void generateDrugEventsFromTrigger_shouldThrowExceptionWhenSinceWhenIsInTheFuture() throws Exception {
    GregorianCalendar gc = new GregorianCalendar();
    gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
    AtomicReference<Date> sinceWhen = new AtomicReference<Date>();
    sinceWhen.set(gc.getTime());
    DrugEventTrigger trigger = new DrugEventTrigger();
    drugEventService.generateDrugEventsFromTrigger(trigger, sinceWhen.get());
}

From source file:org.apache.flume.node.TestApplication.java

private <T extends LifecycleAware> T mockLifeCycle(Class<T> klass) {

    T lifeCycleAware = mock(klass);/*from   w w w.  j  a va  2s .  c  o  m*/

    final AtomicReference<LifecycleState> state = new AtomicReference<LifecycleState>();

    state.set(LifecycleState.IDLE);

    when(lifeCycleAware.getLifecycleState()).then(new Answer<LifecycleState>() {
        @Override
        public LifecycleState answer(InvocationOnMock invocation) throws Throwable {
            return state.get();
        }
    });

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            state.set(LifecycleState.START);
            return null;
        }
    }).when(lifeCycleAware).start();

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            state.set(LifecycleState.STOP);
            return null;
        }
    }).when(lifeCycleAware).stop();

    return lifeCycleAware;
}

From source file:de.codesourcery.eve.skills.market.impl.EveCentralMarketDataProvider.java

private static Map<InventoryType, PriceInfoQueryResult> runOnEventThread(final PriceCallable r)
        throws PriceInfoUnavailableException {
    if (SwingUtilities.isEventDispatchThread()) {
        return r.call();
    }/*ww w.j ava2s  . c om*/

    final AtomicReference<Map<InventoryType, PriceInfoQueryResult>> result = new AtomicReference<Map<InventoryType, PriceInfoQueryResult>>();
    try {
        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                try {
                    result.set(r.call());
                } catch (PriceInfoUnavailableException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (InvocationTargetException e) {
        Throwable wrapped = e.getTargetException();
        if (wrapped instanceof RuntimeException) {
            if (wrapped.getCause() instanceof PriceInfoUnavailableException) {
                throw (PriceInfoUnavailableException) wrapped.getCause();
            }
            throw (RuntimeException) wrapped;
        } else if (e.getTargetException() instanceof Error) {
            throw (Error) wrapped;
        }
        throw new RuntimeException(e.getTargetException());
    }
    return result.get();
}

From source file:io.soabase.web.filters.LanguageFilter.java

private String getFromQueryString(String queryString, AtomicReference<String> fixedQueryString) {
    if ((queryString != null) && !queryString.trim().isEmpty()) {
        fixedQueryString.set(queryString);
        List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(queryString, Charsets.UTF_8);
        Optional<NameValuePair> first = nameValuePairs.stream()
                .filter(vp -> vp.getName().equals(queryParameterName)).findFirst();
        if (first.isPresent()) {
            try {
                List<NameValuePair> copy = nameValuePairs.stream().filter(p -> p != first.get())
                        .collect(Collectors.toList());
                fixedQueryString.set(URLEncodedUtils.format(copy, Charsets.UTF_8));
                return validate(first.get().getValue());
            } catch (IllegalArgumentException ignore) {
                log.debug("Query param set to invalid language", first.get());
            }/*from w  w  w.j  ava2 s.  c  om*/
        }
    }
    return null;
}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpClientThreadingTest.java

private Thread subscribeWaitAndGetEmissionThread(Observable<CaravanHttpResponse> rxResponse)
        throws InterruptedException {

    AtomicReference<Thread> observerThread = new AtomicReference<>();
    AtomicReference<Throwable> error = new AtomicReference<>();

    rxResponse.subscribe(response -> observerThread.set(Thread.currentThread()), ex -> error.set(ex));

    while (observerThread.get() == null && error.get() == null) {
        Thread.sleep(1);/* ww w.  j  a va 2  s  .com*/
    }

    if (error.get() != null) {
        throw new RuntimeException("The response observable emitted an exception.", error.get());
    }

    return observerThread.get();
}

From source file:jduagui.Controller.java

public static void getExtensions(String startPath, Map<String, Extension> exts) throws IOException {
    final AtomicReference<String> extension = new AtomicReference<>("");
    final File f = new File(startPath);
    final String str = "";
    Path path = Paths.get(startPath);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/*from  ww  w.ja  va2s .  c o m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            storageCache.put(file.toAbsolutePath().toString(), attrs.size());
            extension.set(FilenameUtils.getExtension(file.toAbsolutePath().toString()));

            if (extension.get().equals(str)) {
                if (exts.containsKey(noExt)) {
                    exts.get(noExt).countIncrement();
                    exts.get(noExt).increaseSize(attrs.size());
                } else {
                    exts.put(noExt, new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            } else {

                if (exts.containsKey(extension.get())) {
                    exts.get(extension.get()).countIncrement();
                    exts.get(extension.get()).increaseSize(attrs.size());
                } else {
                    exts.put(extension.get(), new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:org.apache.tomee.jul.handler.rotating.LocalFileHandlerTest.java

@Test
public void logAndRotate() throws IOException {
    final File out = new File("target/LocalFileHandlerTest/logs/");
    if (out.exists()) {
        for (final File file : asList(out.listFiles(new FileFilter() {
            @Override// ww  w  .  j  a  v  a 2 s.  co  m
            public boolean accept(final File pathname) {
                return pathname.getName().startsWith("test");
            }
        }))) {
            if (!file.delete()) {
                file.deleteOnExit();
            }
        }
    }

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("day1");
    config.put("filenamePattern", "target/LocalFileHandlerTest/logs/test.%s.%d.log");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");
    config.put("formatter", MessageOnlyFormatter.class.getName());

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    final File[] logFiles = out.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File pathname) {
            return pathname.getName().startsWith("test");
        }
    });
    final Set<String> logFilesNames = new HashSet<>();
    for (final File f : logFiles) {
        logFilesNames.add(f.getName());
    }
    assertEquals(2, logFiles.length);
    assertEquals(new HashSet<>(asList("test.day1.0.log", "test.day1.1.log")), logFilesNames);

    try (final InputStream is = new FileInputStream(new File(out, "test.day1.1.log"))) {
        final List<String> lines = IOUtils.readLines(is);
        assertEquals(19, lines.size());
        assertEquals(string10chars, lines.iterator().next());
    }

    final long firstFileLen = new File(out, "test.day1.0.log").length();
    assertTrue(firstFileLen >= 1024 * 10 && firstFileLen < 1024 * 10 + (1 + string10chars.getBytes().length));

    // now change of day
    today.set("day2");
    try { // ensure we tets the date
        Thread.sleep(1500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    handler.publish(new LogRecord(Level.INFO, string10chars));
    assertTrue(new File(out, "test.day2.0.log").exists());

    handler.close();
}

From source file:org.encuestame.core.test.integration.IntegrationTestCase.java

@Test
public void shouldAcceptBites() throws Exception {
    String message = "Test Message :" + dateFormat.format(Calendar.getInstance().getTime());

    // String message = "http://google.com";

    final AtomicReference<Message<?>> received = new AtomicReference<Message<?>>();
    bites.subscribe(new MessageHandler() {
        public void handleMessage(Message<?> message) throws MessagingException {
            received.set(message);
        }/*  www  .j a  v a 2  s.co m*/
    });
    twitterAdapter.publishTweet(message);
    // assertThat(((String) received.get().getPayload()), is(message));
    // assertThat(received.get(), hasPayload(message));
}