Example usage for java.util.concurrent.atomic AtomicReference get

List of usage examples for java.util.concurrent.atomic AtomicReference get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference get.

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.bfd.harpc.monitor.RpcMonitor.java

/**
 * ???/*from   w  w  w  .j  ava 2s. c  o m*/
 * <p>
 */
protected void send() {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Start send statistics to zookeeper!");
    }

    // 
    for (Map.Entry<ServerNode, AtomicReference<StatisticsInfo>> entry : statisticsMap.entrySet()) {
        // ??
        ServerNode serverNode = entry.getKey();
        AtomicReference<StatisticsInfo> reference = entry.getValue();
        StatisticsInfo numbers;
        do {
            numbers = reference.get();
        } while (!reference.compareAndSet(numbers, null)); // ?

        StatisticsInfo info = new StatisticsInfo();
        if (numbers != null) {
            info.setSuccess(numbers.getSuccess());
            info.setFailure(numbers.getFailure());
            info.setMaxtime(numbers.getMaxtime());
            info.setMintime(numbers.getMintime());
            info.setAvgtime(numbers.getAvgtime());

            startTimeMap.putIfAbsent(serverNode, startTime);
            long useTime = System.currentTimeMillis() - startTimeMap.get(serverNode);
            startTimeMap.put(serverNode, System.currentTimeMillis()); // ?

            info.setQps(1000 / (useTime / (float) (numbers.getSuccess() + numbers.getFailure())));
        }

        // ???
        sendToZookeeper(serverNode, info, false);
    }
    // ??clientservernode????
    startTime = System.currentTimeMillis();

    // 
    for (Map.Entry<ServerNode, AtomicReference<StatisticsInfo>> entry : totalStatisticsMap.entrySet()) {
        // ??
        ServerNode serverNode = entry.getKey();
        AtomicReference<StatisticsInfo> reference = entry.getValue();
        StatisticsInfo numbers = reference.get();

        StatisticsInfo info = new StatisticsInfo();
        if (numbers != null) {
            info.setSuccess(numbers.getSuccess());
            info.setFailure(numbers.getFailure());
            info.setMaxtime(numbers.getMaxtime());
            info.setMintime(numbers.getMintime());
            info.setAvgtime(numbers.getAvgtime());
            long useTime = System.currentTimeMillis() - beginTime;
            info.setQps(1000 / (useTime / (float) (numbers.getSuccess() + numbers.getFailure())));
        }

        // ???
        sendToZookeeper(serverNode, info, true);
    }
}

From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandler.java

private boolean tryParseTfsLink(final String tfsLink) {
    final String decodedTfsLink;
    try {/* www  . jav a 2 s. co  m*/
        decodedTfsLink = new String(Base64.decodeBase64(tfsLink), "UTF-8"); //$NON-NLS-1$
    } catch (final UnsupportedEncodingException e) {
        log.error("Incorrectly encoded the tfslink query parameter in the protocol handler URI", e); //$NON-NLS-1$
        return false;
    }

    final String[] tfsLinkItems = decodedTfsLink.split("&"); //$NON-NLS-1$
    Map<String, AtomicReference<String>> tfsLinkItemMap = prepareTfsLinkItemMap();

    for (final String tfsLinkItem : tfsLinkItems) {
        final int idx = tfsLinkItem.indexOf("="); //$NON-NLS-1$

        final String itemName;
        final String itemValue;
        if (idx < 0) {
            itemName = tfsLinkItem;
            itemValue = StringUtil.EMPTY;
        } else {
            itemName = tfsLinkItem.substring(0, idx);
            itemValue = tfsLinkItem.substring(idx + 1);
        }

        if (tfsLinkItemMap.containsKey(itemName)) {
            log.info(MessageFormat.format("                          {0}={1}", //$NON-NLS-1$
                    itemName, itemValue));

            tfsLinkItemMap.get(itemName).set(itemValue);
        }
    }

    if (tfsLinkItemMap.get(PROTOCOL_HANDLER_SERVER_URL_ITEM).get() != null) {
        /*
         * A temporary patch. Should be removed after the TFS server is
         * fixed and sends a collection URL instead of server URL and
         * collection ID.
         */
        final URI cloneUrl = URIUtils.newURI(tfsLinkItemMap.get(PROTOCOL_HANDLER_CLONE_URL_ITEM).get());
        if (ServerURIUtils.isHosted(cloneUrl)) {
            final URI uriCandidate = URIUtils.newURI(cloneUrl.getScheme(), cloneUrl.getAuthority());
            tfsLinkItemMap.get(PROTOCOL_HANDLER_COLLECTION_URL_ITEM).set(uriCandidate.toASCIIString());
        }
    }

    if (tfsLinkItemMap.get(PROTOCOL_HANDLER_COLLECTION_URL_ITEM).get() == null) {
        tfsLinkItemMap.remove(PROTOCOL_HANDLER_COLLECTION_URL_ITEM);
        isCollectionUrlAvailable = false;
    } else {
        tfsLinkItemMap.remove(PROTOCOL_HANDLER_COLLECTION_ID_ITEM);
        tfsLinkItemMap.remove(PROTOCOL_HANDLER_SERVER_URL_ITEM);
        isCollectionUrlAvailable = true;
    }

    for (final AtomicReference<String> value : tfsLinkItemMap.values()) {
        if (value.get() == null) {
            return false;
        }
    }

    return true;
}

From source file:eu.eubrazilcc.lvl.storage.TokenCollectionTest.java

@Test
public void test() {
    System.out.println("TokenCollectionTest.test()");
    try {/*from  w  w w. j  ava 2s.c o m*/
        final Collection<String> scopes = newArrayList("scope1", "scope2", "scope2/username1", "scope3,a");
        // insert
        final AccessToken accessToken = AccessToken.builder().token("1234567890abcdEFGhiJKlMnOpqrstUVWxyZ")
                .issuedAt(currentTimeMillis() / 1000l).expiresIn(23l).ownerId("username1").scope(scopes)
                .build();
        TOKEN_DAO.insert(accessToken);

        // find
        AccessToken accessToken2 = TOKEN_DAO.find(accessToken.getToken());
        assertThat("access token is not null", accessToken2, notNullValue());
        assertThat("access token coincides with original", accessToken2, equalTo(accessToken));
        System.out.println(accessToken2.toString());

        // update
        accessToken.setExpiresIn(604800l);
        TOKEN_DAO.update(accessToken);

        // find after update
        accessToken2 = TOKEN_DAO.find(accessToken.getToken());
        assertThat("access token is not null", accessToken2, notNullValue());
        assertThat("access token coincides with original", accessToken2, equalTo(accessToken));
        System.out.println(accessToken2.toString());

        // list by owner Id
        List<AccessToken> accessTokens = TOKEN_DAO.listByOwnerId(accessToken.getOwnerId());
        assertThat("access tokens are not null", accessTokens, notNullValue());
        assertThat("access tokens are not empty", !accessTokens.isEmpty(), equalTo(true));
        assertThat("number of access tokens coincides with expected", accessTokens.size(), equalTo(1));
        assertThat("access tokens coincide with original", accessTokens.get(0), equalTo(accessToken));

        // check validity         
        boolean validity = TOKEN_DAO.isValid(accessToken.getToken());
        assertThat("access token is valid", validity, equalTo(true));

        final AtomicReference<String> ownerIdRef = new AtomicReference<String>();
        validity = TOKEN_DAO.isValid(accessToken.getToken(), ownerIdRef);
        assertThat("access token is valid using target scope", validity, equalTo(true));
        assertThat("owner id coincides is not null", ownerIdRef.get(), notNullValue());
        assertThat("owner id coincides with expected", ownerIdRef.get(), equalTo(accessToken.getOwnerId()));

        // remove
        TOKEN_DAO.delete(accessToken.getToken());
        final long numRecords = TOKEN_DAO.count();
        assertThat("number of access tokens stored in the database coincides with expected", numRecords,
                equalTo(0l));

        // pagination
        final List<String> ids = newArrayList();
        for (int i = 0; i < 11; i++) {
            final AccessToken accessToken3 = AccessToken.builder().token(Integer.toString(i)).build();
            ids.add(accessToken3.getToken());
            TOKEN_DAO.insert(accessToken3);
        }
        final int size = 3;
        int start = 0;
        accessTokens = null;
        final MutableLong count = new MutableLong(0l);
        do {
            accessTokens = TOKEN_DAO.list(start, size, null, null, null, count);
            if (accessTokens.size() != 0) {
                System.out.println("Paging: first item " + start + ", showing " + accessTokens.size() + " of "
                        + count.getValue() + " items");
            }
            start += accessTokens.size();
        } while (!accessTokens.isEmpty());
        for (final String id2 : ids) {
            TOKEN_DAO.delete(id2);
        }
        TOKEN_DAO.stats(System.out);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("TokenCollectionTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("TokenCollectionTest.test() has finished");
    }
}

From source file:com.chiorichan.scheduler.ChioriScheduler.java

private void addTask(final ChioriTask task) {
    final AtomicReference<ChioriTask> tail = this.tail;
    ChioriTask tailTask = tail.get();
    while (!tail.compareAndSet(tailTask, task)) {
        tailTask = tail.get();//from ww w.  ja  v a  2s  . c  o  m
    }
    tailTask.setNext(task);
}

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);/* w w  w  .ja  v a 2  s  .co m*/

    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.microsoft.tfs.client.common.ui.console.ConsoleCoreEventListener.java

private void onGet(final GetEvent e) {
    e.getStatus();//from  ww w  .j  a  va  2  s. c om

    final AtomicReference<String> errorHolder = new AtomicReference<String>();
    final String messageString = e.getMessage(null, errorHolder);

    Message message;
    if (errorHolder.get() != null) {
        message = new Message(MessageType.ERROR, errorHolder.get());
    } else {
        message = new Message(MessageType.INFO, messageString);
    }

    printMessageToConsole(message);
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

private String getBuildProjectRelativePath() {
    final String buildFileLocation = buildDefinition.getConfigurationFolderPath();
    final AtomicReference<String> path = new AtomicReference<String>();

    if (GitProperties.parseGitItemUrl(buildFileLocation, null, null, null, path)) {
        return path.get() + GitProperties.PathSeparator + BuildConstants.PROJECT_FILE_NAME;
    }//from  w  w w. j  ava 2s  . c  o m

    return null;
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

private String getBuildResponseRelativePath() {
    final String buildFileLocation = buildDefinition.getConfigurationFolderPath();
    final AtomicReference<String> path = new AtomicReference<String>();

    if (GitProperties.parseGitItemUrl(buildFileLocation, null, null, null, path)) {
        return path.get() + GitProperties.PathSeparator + BuildConstants.RESPONSE_FILE_NAME;
    }/*w  w w  .  j a v a2  s.  c  o m*/

    return null;
}

From source file:com.example.app.ui.DemoUserProfileEditor.java

@Override
public ModificationState getModificationState() {
    if (!isInited())
        return ModificationState.UNCHANGED;
    final AtomicReference<ModificationState> state = new AtomicReference<>(ModificationState.UNCHANGED);
    _forEach(value -> {/*from   www . j av  a 2 s.  c  o  m*/
        if (!state.get().isModified() && value.getModificationState().isModified())
            state.set(ModificationState.CHANGED);
    });
    return state.get();
}

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
 *///  w  ww. ja  v a2s  . com
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);
    }
}