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.twitter.aurora.scheduler.app.SchedulerIT.java

private HostAndPort awaitSchedulerReady() throws Exception {
    return executor.submit(new Callable<HostAndPort>() {
        @Override/*from w w w  .  j  a  va  2  s.c om*/
        public HostAndPort call() throws Exception {
            final AtomicReference<HostAndPort> thriftEndpoint = Atomics.newReference();
            ServerSet schedulerService = new ServerSetImpl(zkClient, SERVERSET_PATH);
            final CountDownLatch schedulerReady = new CountDownLatch(1);
            schedulerService.watch(new HostChangeMonitor<ServiceInstance>() {
                @Override
                public void onChange(ImmutableSet<ServiceInstance> hostSet) {
                    if (!hostSet.isEmpty()) {
                        Endpoint endpoint = Iterables.getOnlyElement(hostSet).getServiceEndpoint();
                        thriftEndpoint.set(HostAndPort.fromParts(endpoint.getHost(), endpoint.getPort()));
                        schedulerReady.countDown();
                    }
                }
            });
            // A timeout is used because certain types of assertion errors (mocks) will not surface
            // until the main test thread exits this body of code.
            assertTrue(schedulerReady.await(5L, TimeUnit.MINUTES));
            return thriftEndpoint.get();
        }
    }).get();
}

From source file:org.apache.hadoop.hbase.quotas.TestQuotaStatusRPCs.java

@Test
public void testQuotaStatusFromMaster() throws Exception {
    final long sizeLimit = 1024L * 10L; // 10KB
    final long tableSize = 1024L * 5; // 5KB
    final long nsLimit = Long.MAX_VALUE;
    final int numRegions = 10;
    final TableName tn = helper.createTableWithRegions(numRegions);

    // Define the quota
    QuotaSettings settings = QuotaSettingsFactory.limitTableSpace(tn, sizeLimit,
            SpaceViolationPolicy.NO_INSERTS);
    TEST_UTIL.getAdmin().setQuota(settings);
    QuotaSettings nsSettings = QuotaSettingsFactory.limitNamespaceSpace(tn.getNamespaceAsString(), nsLimit,
            SpaceViolationPolicy.NO_INSERTS);
    TEST_UTIL.getAdmin().setQuota(nsSettings);

    // Write at least `tableSize` data
    helper.writeData(tn, tableSize);/*from  w  w  w .  j a  va  2  s  . co m*/

    final Connection conn = TEST_UTIL.getConnection();
    // Make sure the master has a snapshot for our table
    Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() {
        @Override
        public boolean evaluate() throws Exception {
            SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn);
            LOG.info("Table snapshot after initial ingest: " + snapshot);
            if (snapshot == null) {
                return false;
            }
            return snapshot.getLimit() == sizeLimit && snapshot.getUsage() > 0L;
        }
    });
    final AtomicReference<Long> nsUsage = new AtomicReference<>();
    // If we saw the table snapshot, we should also see the namespace snapshot
    Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000 * 1000, new Predicate<Exception>() {
        @Override
        public boolean evaluate() throws Exception {
            SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn.getNamespaceAsString());
            LOG.debug("Namespace snapshot after initial ingest: " + snapshot);
            if (snapshot == null) {
                return false;
            }
            nsUsage.set(snapshot.getUsage());
            return snapshot.getLimit() == nsLimit && snapshot.getUsage() > 0;
        }
    });

    try {
        helper.writeData(tn, tableSize * 2L);
    } catch (RetriesExhaustedWithDetailsException | SpaceLimitingException e) {
        // Pass
    }

    // Wait for the status to move to violation
    Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() {
        @Override
        public boolean evaluate() throws Exception {
            SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn);
            LOG.info("Table snapshot after second ingest: " + snapshot);
            if (snapshot == null) {
                return false;
            }
            return snapshot.getQuotaStatus().isInViolation();
        }
    });
    // The namespace should still not be in violation, but have a larger usage than previously
    Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() {
        @Override
        public boolean evaluate() throws Exception {
            SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn.getNamespaceAsString());
            LOG.debug("Namespace snapshot after second ingest: " + snapshot);
            if (snapshot == null) {
                return false;
            }
            return snapshot.getUsage() > nsUsage.get() && !snapshot.getQuotaStatus().isInViolation();
        }
    });
}

From source file:org.commonjava.util.partyline.JoinableFileManager.java

/**
 * If there is an active {@link JoinableFile}, call {@link JoinableFile#joinStream()} and return it to the user.
 * Otherwise, open a new {@link FileInputStream} to the specified file and pass the result back to the user. If the
 * file is locked for reads, wait for the specified milliseconds before giving up.
 *//*from w w w.  j a  va  2  s .  co m*/
public InputStream openInputStream(final File file, final long timeout)
        throws IOException, InterruptedException {
    logger.trace(">>>OPEN INPUT: {} with timeout: {}", file, timeout);
    AtomicReference<InterruptedException> interrupt = new AtomicReference<>();
    InputStream stream = locks.setOrJoinFile(file, null, false, timeout, TimeUnit.MILLISECONDS, (result) -> {
        if (result == null) {
            throw new IOException("Could not open input stream to: " + file + " in " + timeout + "ms.");
        }

        try {
            return result.joinStream();
        } catch (InterruptedException e) {
            interrupt.set(e);
        }

        return null;
    });

    InterruptedException ie = interrupt.get();
    if (ie != null) {
        throw ie;
    }

    addToContext("INPUT@" + System.nanoTime() + ": " + file, stream);

    return stream;
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> recomputeFunction) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//from   ww w  . java2 s .  c om
    checkNotNull(recomputeFunction, "Recompute function cannot be null");

    String encodedKey = encodeKey(key);
    AtomicReference<MapDelegateEvent.Type> update = new AtomicReference<>();
    AtomicReference<MapValue> previousValue = new AtomicReference<>();
    MapValue computedValue = items.compute(encodedKey, (k, mv) -> {
        previousValue.set(mv);
        V newRawValue = recomputeFunction.apply(key, mv == null ? null : mv.get(this::decodeValue));
        byte[] newEncodedValue = encodeValue(newRawValue);
        if (mv != null && Arrays.equals(newEncodedValue, mv.get())) {
            // value was not updated
            return mv;
        }
        MapValue newValue = new MapValue(newEncodedValue,
                timestampProvider.get(Maps.immutableEntry(key, newRawValue)));
        if (mv == null) {
            update.set(INSERT);
            return newValue;
        } else if (newValue.isNewerThan(mv)) {
            update.set(UPDATE);
            return newValue;
        } else {
            return mv;
        }
    });
    if (update.get() != null) {
        notifyPeers(new UpdateEntry(encodedKey, computedValue), peerUpdateFunction
                .select(Maps.immutableEntry(key, computedValue.get(this::decodeValue)), membershipService));
        MapDelegateEvent.Type updateType = computedValue.isTombstone() ? REMOVE : update.get();
        V value = computedValue.isTombstone()
                ? previousValue.get() == null ? null : previousValue.get().get(this::decodeValue)
                : computedValue.get(this::decodeValue);
        if (value != null) {
            notifyListeners(new MapDelegateEvent<>(updateType, key, value));
        }
        return value;
    }
    return computedValue.get(this::decodeValue);
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void notModified() throws Exception {
    int code = 304;
    statusCode.set(code);//from   w w  w .ja v a 2s .c  om
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/notModified")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            latch.countDown();
            throwable.set(t);
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    assertEquals(expected, statusCounts);
    Assert.assertNull(throwable.get());
}

From source file:io.undertow.server.handlers.sse.ServerSentEventTestCase.java

@Test
public void testProgressiveSSEWithCompression() throws IOException {
    final AtomicReference<ServerSentEventConnection> connectionReference = new AtomicReference<>();
    DecompressingHttpClient client = new DecompressingHttpClient(new TestHttpClient());
    try {//from  w w  w  .j  a  v a  2s .co  m

        DefaultServer.setRootHandler(new EncodingHandler(new ContentEncodingRepository()
                .addEncodingHandler("deflate", new DeflateEncodingProvider(), 50))
                        .setNext(new ServerSentEventHandler(new ServerSentEventConnectionCallback() {
                            @Override
                            public void connected(ServerSentEventConnection connection, String lastEventId) {
                                connectionReference.set(connection);
                                connection.send("msg 1", new ServerSentEventConnection.EventCallback() {
                                    @Override
                                    public void done(ServerSentEventConnection connection, String data,
                                            String event, String id) {

                                    }

                                    @Override
                                    public void failed(ServerSentEventConnection connection, String data,
                                            String event, String id, IOException e) {
                                        e.printStackTrace();
                                        IoUtils.safeClose(connection);
                                    }
                                });
                            }
                        })));

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        InputStream stream = result.getEntity().getContent();
        assertData(stream, "data:msg 1\n\n");
        connectionReference.get().send("msg 2");
        assertData(stream, "data:msg 2\n\n");
        connectionReference.get().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void relativeRedirect() throws Exception {
    int code = 200;
    statusCode.set(code);//from w w w. ja va2s . c  om
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(302, 2);
    expected.addAndGet(code, 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/relativeRedirect")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            latch.countDown();
            throwable.set(t);
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    assertEquals(expected, statusCounts);
}

From source file:net.technicpack.launchercore.install.InstalledPack.java

private boolean loadCachedImage(AtomicReference<BufferedImage> image, File file, String url, String md5) {
    try {//w w w  . j  a v a  2s. c om
        if (!file.exists())
            return false;

        boolean reloadImage = (url.isEmpty() || md5.isEmpty());

        if (!reloadImage) {
            String fileMd5 = MD5Utils.getMD5(file);

            if (fileMd5 != null && !fileMd5.isEmpty())
                reloadImage = fileMd5.equalsIgnoreCase(md5);
        }

        if (reloadImage) {
            BufferedImage newImage;
            newImage = ImageIO.read(file);
            image.set(newImage);
            return true;
        }
    } catch (IIOException e) {
        Utils.getLogger().log(Level.INFO, "Failed to load image " + file.getAbsolutePath() + " from file.");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

From source file:org.eclipse.mylyn.internal.reviews.ui.dialogs.CommentInputDialog.java

private boolean performOperation(final IComment comment) {
    final IReviewItem item = reviewitem;
    final AtomicReference<IStatus> result = new AtomicReference<IStatus>();

    if (isSave || isDiscard) {
        final Job job = new Job(Messages.CommandServerOperation) {

            @Override//from   www .  j a  v  a  2  s  .c om
            protected IStatus run(IProgressMonitor monitor) {
                IStatus status = null;
                if (isSave) {
                    status = reviewBehavior.addComment(item, comment, monitor);
                    if (status.isOK()) {
                        result.set(status);
                        updateClient(comment, item);
                        return Status.OK_STATUS;
                    }
                } else {
                    status = reviewBehavior.discardComment(item, comment, monitor);
                    if (status.isOK()) {
                        result.set(status);
                        updateClient(comment, item);
                        return Status.OK_STATUS;
                    }
                }
                processServerError(status.getMessage());

                return Status.OK_STATUS;
            }

        };
        job.setUser(true);
        job.schedule();
    }

    return true;

}

From source file:com.netflix.iep.http.RxHttpTest.java

@Test
public void redirectResponseMissingLocation() throws Exception {
    int code = 302;
    statusCode.set(code);/* w  w w  . j a  v  a2 s. c o  m*/
    redirects.set(2);
    AtomicIntegerArray expected = copy(statusCounts);
    expected.addAndGet(code, 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get(uri("/redirectNoLocation")).subscribe(Actions.empty(), new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            latch.countDown();
            throwable.set(t);
        }
    }, new Action0() {
        @Override
        public void call() {
            latch.countDown();
        }
    });

    latch.await();
    assertEquals(expected, statusCounts);
    Assert.assertNotNull(throwable.get());
}