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

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.alibaba.jstorm.daemon.supervisor.SyncProcessEvent.java

/**
 * @param conf/*from  w  w w.  j a  va2  s  .  c o  m*/
 * @param localState
 * @param workerThreadPids
 * @param supervisorId
 * @param sharedContext
 * @param workerThreadPidsReadLock
 * @param workerThreadPidsWriteLock
 */
public SyncProcessEvent(String supervisorId, Map conf, LocalState localState,
        ConcurrentHashMap<String, String> workerThreadPids, IContext sharedContext,
        WorkerReportError workerReportError) {

    this.supervisorId = supervisorId;

    this.conf = conf;

    this.localState = localState;

    this.workerThreadPids = workerThreadPids;

    // right now, sharedContext is null
    this.sharedContext = sharedContext;

    this.sandBoxMaker = new SandBoxMaker(conf);

    this.workerIdToStartTimeAndPort = new HashMap<String, Pair<Integer, Integer>>();

    this.needDownloadTopologys = new AtomicReference<Set>();

    if (ConfigExtension.isEnableCgroup(conf)) {
        cgroupManager = new CgroupManager(conf);
    }

    killingWorkers = new HashMap<String, Integer>();
    this.workerReportError = workerReportError;
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CheckBuildFileExistsCommand.java

private IStatus checkGitVC(final IProgressMonitor progressMonitor, final String itemPath) {
    try {/*from w ww .j  a va2 s.c  om*/
        final AtomicReference<String> projectName = new AtomicReference<String>();
        final AtomicReference<String> repositoryName = new AtomicReference<String>();
        final AtomicReference<String> branchName = new AtomicReference<String>();
        final AtomicReference<String> path = new AtomicReference<String>();

        if (!GitProperties.parseGitItemUrl(itemPath, projectName, repositoryName, branchName, path)) {
            final String messageFormat = Messages
                    .getString("CheckBuildFileExistsCommand.WrongBuildPojectUriErrorFormat"); //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, itemPath);
            return new Status(IStatus.ERROR, TFSTeamBuildPlugin.PLUGIN_ID, Status.OK, message,
                    new BuildException(message));
        }

        final ICommandExecutor commandExecutor = new CommandExecutor();
        final QueryGitItemsCommand test = new QueryGitItemsCommand(versionControl, projectName.get(),
                repositoryName.get(), branchName.get(), path.get());

        final IStatus status = commandExecutor.execute(test);

        buildFileExists = status.isOK() && test.getRepositoryItems().size() > 0;
    } catch (final Exception e) {
        // encountered a version control exception (i.e. file does not
        // exist). Ignore it
        // but log just in case it was something else.
        buildFileExists = false;
        log.warn("Ignoring exception when checking for TFSBuild.proj in " + folderPath); //$NON-NLS-1$
    }

    return Status.OK_STATUS;
}

From source file:com.datatorrent.lib.io.jms.AbstractJMSInputOperator.java

public AbstractJMSInputOperator() {
    counters = new BasicCounters<MutableLong>(MutableLong.class);
    throwable = new AtomicReference<Throwable>();
    pendingAck = Sets.newHashSet();/*from   w w  w .j av  a 2  s . co m*/
    windowDataManager = new FSWindowDataManager();

    lock = new Lock();

    //Recovery state is a linked hash map to maintain the order of tuples.
    currentWindowRecoveryState = Maps.newLinkedHashMap();
    holdingBuffer = new ArrayBlockingQueue<Message>(bufferSize) {
        private static final long serialVersionUID = 201411151139L;

        @SuppressWarnings("Contract")
        @Override
        public boolean add(Message message) {
            synchronized (lock) {
                try {
                    return messageConsumed(message) && super.add(message);
                } catch (JMSException e) {
                    LOG.error("message consumption", e);
                    throwable.set(e);
                    throw new RuntimeException(e);
                }
            }
        }
    };
}

From source file:org.ldp4j.server.IntegrationTestHelper.java

public String httpRequest(final HttpUriRequest request) throws Exception {
    final AtomicReference<String> body = new AtomicReference<String>();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            body.set(responseBody);/*from  www.  j ava2 s.  co  m*/
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return body.get();
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncQueryIT.java

@Test
public void should_return_rows_for_native_query_async() throws Exception {
    CompleteBean entity1 = builder().randomId().name("DuyHai").age(35L).addFriends("foo", "bar")
            .addFollowers("George", "Paul").addPreference(1, "FR").addPreference(2, "Paris")
            .addPreference(3, "75014").version(CounterBuilder.incr(15L)).buid();

    CompleteBean entity2 = builder().randomId().name("John DOO").age(35L).addFriends("qux", "twix")
            .addFollowers("Isaac", "Lara").addPreference(1, "US").addPreference(2, "NewYork")
            .version(CounterBuilder.incr(17L)).buid();

    asyncManager.insert(entity1).getImmediately();
    asyncManager.insert(entity2).getImmediately();

    final RegularStatement statement = select("name", "age_in_years", "friends", "followers", "preferences")
            .from("CompleteBean").where(eq("id", bindMarker("id")));

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override//w w w  .ja  va2s  . c  om
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    final AchillesFuture<List<TypedMap>> future1 = asyncManager.nativeQuery(statement, entity1.getId())
            .get(successCallBack);
    final AchillesFuture<List<TypedMap>> future2 = asyncManager.nativeQuery(statement, entity2.getId()).get();

    latch.await();

    final List<TypedMap> typedMaps1 = future1.get();
    assertThat(typedMaps1).hasSize(1);
    TypedMap typedMap1 = typedMaps1.get(0);

    while (!future2.isDone()) {
        Thread.sleep(2);
    }

    final List<TypedMap> typedMaps2 = future2.get();
    assertThat(typedMaps2).hasSize(1);
    TypedMap typedMap2 = typedMaps2.get(0);

    assertThat(typedMap1.get("name")).isEqualTo("DuyHai");
    assertThat(typedMap1.get("age_in_years")).isEqualTo(35L);
    assertThat(typedMap1.<List<String>>getTyped("friends")).containsExactly("foo", "bar");
    assertThat(typedMap1.<Set<String>>getTyped("followers")).contains("George", "Paul");
    Map<Integer, String> preferences1 = typedMap1.getTyped("preferences");
    assertThat(preferences1.get(1)).isEqualTo("FR");
    assertThat(preferences1.get(2)).isEqualTo("Paris");
    assertThat(preferences1.get(3)).isEqualTo("75014");

    assertThat(typedMap2.get("name")).isEqualTo("John DOO");
    assertThat(typedMap2.get("age_in_years")).isEqualTo(35L);
    assertThat(typedMap2.<List<String>>getTyped("friends")).containsExactly("qux", "twix");
    assertThat(typedMap2.<Set<String>>getTyped("followers")).contains("Isaac", "Lara");
    Map<Integer, String> preferences2 = typedMap2.getTyped("preferences");
    assertThat(preferences2.get(1)).isEqualTo("US");
    assertThat(preferences2.get(2)).isEqualTo("NewYork");

    latch.await();
    assertThat(successSpy.get()).isNotNull().isInstanceOf(List.class);
}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testRejectNAWS() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, false, false);
    testOptionValue(new Supplier<TelnetHandler>() {
        @Override//from   ww w. ja  v a 2  s .  c o  m
        public TelnetHandler get() {
            return new TelnetHandler() {
                @Override
                protected void onOpen(TelnetConnection conn) {
                    conn.writeDoOption(Option.NAWS);
                }

                @Override
                protected void onNAWS(boolean naws) {
                    serverValue.set(naws);
                    testComplete();
                }

                @Override
                protected void onSize(int width, int height) {
                    super.onSize(width, height);
                }
            };
        }
    }, optionHandler);
    assertEquals(false, serverValue.get());
    assertEquals(false, optionHandler.getAcceptLocal());
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritUtil.java

private <T> T doAccessToGerritWithModalProgress(@NotNull final Project project,
        @NotNull final ThrowableComputable<T, Exception> computable) {
    final AtomicReference<T> result = new AtomicReference<T>();
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    ProgressManager.getInstance().run(new Task.Modal(project, "Access to Gerrit", true) {
        public void run(@NotNull ProgressIndicator indicator) {
            try {
                result.set(computable.compute());
            } catch (Exception e) {
                exception.set(e);//from w ww.j  av a  2 s  .c  om
            }
        }
    });
    //noinspection ThrowableResultOfMethodCallIgnored
    if (exception.get() == null) {
        return result.get();
    }
    throw Throwables.propagate(exception.get());
}

From source file:com.jeremydyer.iot.GPIORESTProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    final ProcessorLog log = this.getLogger();
    final AtomicReference<Integer> value = new AtomicReference<>();

    final FlowFile flowfile = session.get();
    final Integer delayThreshold = context.getProperty(PROP_SWITCH_DELAY_THRESHOLD).asInteger();

    session.read(flowfile, new InputStreamCallback() {
        @Override/*from w  w w  .j  ava 2  s . c  o  m*/
        public void process(InputStream in) throws IOException {
            try {
                String json = IOUtils.toString(in);
                int numFaces = JsonPath.read(json, "$.faces");
                value.set(numFaces);
            } catch (Exception ex) {
                getLogger().error("Failed to process face detection context", ex);
                session.transfer(flowfile, REL_FAILURE);
            }
        }
    });

    // Write the results to an attribute
    int numFaces = value.get();

    if (CURRENTLY_ON.get()) {
        //Outlet is on. If no faces detected turn off. Else do nothing
        if (numFaces == 0 && (((System.currentTimeMillis() - LAST_SWITCH_TS.get()) / 1000) > delayThreshold)) {
            CURRENTLY_ON.set(false);
            LAST_SWITCH_TS.set(System.currentTimeMillis());
            session.transfer(flowfile, REL_TURN_OFF);
        } else {
            session.transfer(flowfile, REL_NO_CHANGE);
        }
    } else {
        //Outlet is currently turned off
        if (numFaces > 0 && (((System.currentTimeMillis() - LAST_SWITCH_TS.get()) / 1000) > delayThreshold)) {
            CURRENTLY_ON.set(true);
            LAST_SWITCH_TS.set(System.currentTimeMillis());
            session.transfer(flowfile, REL_TURN_ON);
        } else {
            session.transfer(flowfile, REL_NO_CHANGE);
        }
    }

}

From source file:edu.rit.flick.genetics.FastFileDeflator.java

@Override
public File deflate(final Configuration configuration, final File fileIn, final File fileOut) {
    assert fileIn.exists();

    try {/*from  www .j a v  a 2s . c  o m*/
        // Deflate to Directory
        final String outputDirectoryPath = fileOut.getPath()
                .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX);

        final File tmpOutputDirectory = new File(outputDirectoryPath);
        if (tmpOutputDirectory.exists())
            FileUtils.deleteDirectory(tmpOutputDirectory);
        tmpOutputDirectory.mkdirs();

        final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>();

        // Deflate Fast file to a temporary directory
        final Thread deflateToDirectoryThread = new Thread(() -> {
            try {
                // Deflate Fast file to a temporary directory
                deflateToDirectory(fileIn, tmpOutputDirectory);

                // Remove unused buffer space
                removeUnusedBufferSpace(outputDirectoryPath);

                // Compress Directory to a zip file
                deflateToFile(tmpOutputDirectory, fileOut);

                Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get());
            } catch (final Exception e) {
                if (!interrupted)
                    System.err.println(e.getMessage());
            }
        }, "Default_Deflation_Thread");

        // Make cleaning hook
        final Thread cleanHook = new Thread(() -> {
            interrupted = true;
            configuration.setFlag(VERBOSE_FLAG, false);
            configuration.setFlag(DELETE_FLAG, false);
            try {
                if (deflateToDirectoryThread.isAlive())
                    deflateToDirectoryThread.interrupt();

                // Remove unused buffer space
                removeUnusedBufferSpace(outputDirectoryPath);

                // Delete files that were not able to be processed
                FileUtils.deleteQuietly(tmpOutputDirectory);
                System.out.println();
            } catch (final IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }, "Deflation_Cleaning_Thread");

        cleanHookAtomic.set(cleanHook);

        Runtime.getRuntime().addShutdownHook(cleanHook);

        deflateToDirectoryThread.start();
        deflateToDirectoryThread.join();

    } catch (final IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return fileOut;
}

From source file:com.jeremydyer.nifi.processors.google.GoogleSpeechProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from w w w .j  a  va  2 s  .  c  o  m*/
    if (flowFile == null) {
        return;
    }

    try {

        AtomicReference<String> image = new AtomicReference<>();

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream inputStream) throws IOException {
                byte[] bytes = IOUtils.toByteArray(inputStream);
                byte[] encImage = Base64.getEncoder().encode(bytes);
                image.set(new String(encImage));
            }
        });

        AnnotateImageRequest request = new AnnotateImageRequest()
                .setImage(new Image().setContent(new String(image.get()))).setFeatures(ImmutableList
                        .of(new Feature().setType("LANDMARK_DETECTION").setMaxResults(MAX_RESULTS)));

        Vision.Images.Annotate annotate = vision.images()
                .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));

        BatchAnnotateImagesResponse batchResponse = annotate.execute();
        assert batchResponse.getResponses().size() == 1;
        AnnotateImageResponse response = batchResponse.getResponses().get(0);
        if (response.getLandmarkAnnotations() == null) {
            throw new IOException(response.getError() != null ? response.getError().getMessage()
                    : "Unknown error getting image annotations");
        }

        StringBuilder lndMarks = new StringBuilder();

        List<EntityAnnotation> landmarks = response.getLandmarkAnnotations();
        System.out.printf("Found %d landmark%s\n", landmarks.size(), landmarks.size() == 1 ? "" : "s");
        for (EntityAnnotation annotation : landmarks) {
            System.out.printf("\t%s\n", annotation.getDescription());
            lndMarks.append(annotation.getDescription());
            lndMarks.append(", ");
        }

        flowFile = session.putAttribute(flowFile, "landmarks", lndMarks.toString());

        session.transfer(flowFile, REL_SUCCESS);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}