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.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);/*ww w.j ava  2s . c om*/
            }
        }
    });
    //noinspection ThrowableResultOfMethodCallIgnored
    if (exception.get() == null) {
        return result.get();
    }
    throw Throwables.propagate(exception.get());
}

From source file:com.microsoft.tfs.client.common.ui.wizard.common.WizardServerSelectionPage.java

private List<Account> getUserAccounts(final AtomicReference<JwtCredentials> vstsCredentialsHolder,
        final Action<DeviceFlowResponse> deviceFlowCallback) {
    for (int retriesLeft = MAX_CREDENTIALS_RETRIES; retriesLeft > 0; retriesLeft--) {
        final JwtCredentials azureAccessToken = getAzureAccessToken(retriesLeft == MAX_CREDENTIALS_RETRIES,
                deviceFlowCallback);//from w w w . jav a 2s  . c  o  m

        if (azureAccessToken == null) {
            log.info(" Credentials dialog has been cancelled by the user."); //$NON-NLS-1$
            break;
        }

        vstsCredentialsHolder.set(azureAccessToken);

        /*
         * At this point we do not have any connection which HTTPClient we
         * might use to create a TeeClientHandler. Let's create a fake one.
         * We do not use the connection we create here as a real
         * TFSTeamProjectColection. We only use this fake connection object
         * as a source of an HTTPClient configured to use the VSTS
         * credentials provided.
         */
        final TFSConnection vstsConnection = new TFSTeamProjectCollection(URIUtils.VSTS_ROOT_URL,
                azureAccessToken, new UIClientConnectionAdvisor());
        final TeeClientHandler clientHandler = new TeeClientHandler(vstsConnection.getHTTPClient());

        final ProfileHttpClient profileClient = new ProfileHttpClient(clientHandler, URIUtils.VSTS_ROOT_URL);

        try {
            final Profile profile = profileClient.getMyProfile();

            if (profile != null) {
                log.info("Profile ID = " + profile.getId()); //$NON-NLS-1$

                final AccountHttpClient accountClient = new AccountHttpClient(clientHandler,
                        URIUtils.VSTS_ROOT_URL);

                final List<Account> accounts = accountClient.getAccounts(profile.getId());
                log.info("Accounts number = " + accounts.size()); //$NON-NLS-1$

                return accounts;
            }
            break;
        } catch (final Exception e) {
            if (retriesLeft > 1 && (e instanceof VssResourceNotFoundException)) {
                updateCredentials(URIUtils.VSTS_ROOT_URL, null);
            } else {
                log.error("Error connecting to VSTS", e); //$NON-NLS-1$

                final String title = Messages.getString("WizardServerSelectionPage.ErrorConnectingVstsText"); //$NON-NLS-1$

                final String message = (e instanceof VssResourceNotFoundException)
                        ? Messages.getString("WizardServerSelectionPage.VstsAuthFailedText") //$NON-NLS-1$
                        : e.getLocalizedMessage();

                ErrorDialog.openError(getShell(), title, null,
                        new Status(Status.ERROR, TFSCommonUIClientPlugin.PLUGIN_ID, 0, message, e));
                break;
            }
        } finally {
            /*
             * We didn't use any features of the vstsConnection but the
             * HTTPClient. However to release all resources and the
             * infrastructure created for the connection (e.g.
             * ShoultDownManager, HTTPClientReference, Service Clients,
             * etc.), we still should close this connection when leaving the
             * try-catch block.
             */
            try {
                vstsConnection.close();
            } catch (final Exception e) {
                log.error("Absolutelly unexpected error while closing not opened connection", e); //$NON-NLS-1$
            }
        }
    }

    return new ArrayList<Account>();
}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java

@Test
public void testRetryOnConflict() throws InterruptedException {
    final String index = "JresUpdateDocumentTest.testRetryOnConflict".toLowerCase();
    final String type = "test";
    final String id = "warzone";

    final AtomicReference<String> error = new AtomicReference<String>();

    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {
        x.submit(new Runnable() {
            @Override/*from  w ww .  ja  v a2  s  . com*/
            public void run() {
                try {
                    for (int j = 0; j < numIterations; j++) {
                        JresUpdateDocument req = new JresUpdateDocument(index, type, id,
                                ImmutableMap.of("value", 0));
                        req.setRetryOnConflict(numIterations * 10);
                        jres.quest(req);
                    }
                } catch (Exception e) {
                    error.set(e.getMessage());
                }
            }
        });
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    Assert.assertNull("With so many retries, all of these should have gotten through without conflict error",
            error.get());
    jres.quest(new JresRefresh(index));
    JresGetDocumentReply getReply = jres.quest(new JresGetDocument(index, type, id));
    Map<String, Integer> doc = getReply.getSourceAsType(new TypeReference<Map<String, Integer>>() {
    });
    Assert.assertEquals("Should have been numThreads * numIterations versions committed",
            (Object) (numThreads * numIterations), getReply.getVersion());
}

From source file:org.apache.flink.test.recovery.AbstractTaskManagerProcessFailureRecoveryTest.java

@Test
public void testTaskManagerProcessFailure() {

    final StringWriter processOutput1 = new StringWriter();
    final StringWriter processOutput2 = new StringWriter();
    final StringWriter processOutput3 = new StringWriter();

    ActorSystem jmActorSystem = null;//from www .j  av  a  2 s .c o  m
    Process taskManagerProcess1 = null;
    Process taskManagerProcess2 = null;
    Process taskManagerProcess3 = null;

    File coordinateTempDir = null;

    try {
        // check that we run this test only if the java command
        // is available on this machine
        String javaCommand = getJavaCommandPath();
        if (javaCommand == null) {
            System.out.println("---- Skipping Process Failure test : Could not find java executable ----");
            return;
        }

        // create a logging file for the process
        File tempLogFile = File.createTempFile(getClass().getSimpleName() + "-", "-log4j.properties");
        tempLogFile.deleteOnExit();
        CommonTestUtils.printLog4jDebugConfig(tempLogFile);

        // coordination between the processes goes through a directory
        coordinateTempDir = CommonTestUtils.createTempDirectory();

        // find a free port to start the JobManager
        final int jobManagerPort = NetUtils.getAvailablePort();

        // start a JobManager
        Tuple2<String, Object> localAddress = new Tuple2<String, Object>("localhost", jobManagerPort);

        Configuration jmConfig = new Configuration();
        jmConfig.setString(ConfigConstants.AKKA_WATCH_HEARTBEAT_INTERVAL, "1000 ms");
        jmConfig.setString(ConfigConstants.AKKA_WATCH_HEARTBEAT_PAUSE, "6 s");
        jmConfig.setInteger(ConfigConstants.AKKA_WATCH_THRESHOLD, 9);
        jmConfig.setString(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY, "10 s");
        jmConfig.setString(ConfigConstants.AKKA_ASK_TIMEOUT, "100 s");

        jmActorSystem = AkkaUtils.createActorSystem(jmConfig, new Some<>(localAddress));
        ActorRef jmActor = JobManager
                .startJobManagerActors(jmConfig, jmActorSystem, TestingUtils.defaultExecutor(),
                        TestingUtils.defaultExecutor(), JobManager.class, MemoryArchivist.class)
                ._1();

        // the TaskManager java command
        String[] command = new String[] { javaCommand, "-Dlog.level=DEBUG",
                "-Dlog4j.configuration=file:" + tempLogFile.getAbsolutePath(), "-Xms80m", "-Xmx80m",
                "-classpath", getCurrentClasspath(), TaskManagerProcessEntryPoint.class.getName(),
                String.valueOf(jobManagerPort) };

        // start the first two TaskManager processes
        taskManagerProcess1 = new ProcessBuilder(command).start();
        new CommonTestUtils.PipeForwarder(taskManagerProcess1.getErrorStream(), processOutput1);
        taskManagerProcess2 = new ProcessBuilder(command).start();
        new CommonTestUtils.PipeForwarder(taskManagerProcess2.getErrorStream(), processOutput2);

        // we wait for the JobManager to have the two TaskManagers available
        // since some of the CI environments are very hostile, we need to give this a lot of time (2 minutes)
        waitUntilNumTaskManagersAreRegistered(jmActor, 2, 120000);

        // the program will set a marker file in each of its parallel tasks once they are ready, so that
        // this coordinating code is aware of this.
        // the program will very slowly consume elements until the marker file (later created by the
        // test driver code) is present
        final File coordinateDirClosure = coordinateTempDir;
        final AtomicReference<Throwable> errorRef = new AtomicReference<>();

        // we trigger program execution in a separate thread
        Thread programTrigger = new Thread("Program Trigger") {
            @Override
            public void run() {
                try {
                    testTaskManagerFailure(jobManagerPort, coordinateDirClosure);
                } catch (Throwable t) {
                    t.printStackTrace();
                    errorRef.set(t);
                }
            }
        };

        //start the test program
        programTrigger.start();

        // wait until all marker files are in place, indicating that all tasks have started
        // max 20 seconds
        if (!waitForMarkerFiles(coordinateTempDir, READY_MARKER_FILE_PREFIX, PARALLELISM, 120000)) {
            // check if the program failed for some reason
            if (errorRef.get() != null) {
                Throwable error = errorRef.get();
                error.printStackTrace();
                fail("The program encountered a " + error.getClass().getSimpleName() + " : "
                        + error.getMessage());
            } else {
                // no error occurred, simply a timeout
                fail("The tasks were not started within time (" + 120000 + "msecs)");
            }
        }

        // start the third TaskManager
        taskManagerProcess3 = new ProcessBuilder(command).start();
        new CommonTestUtils.PipeForwarder(taskManagerProcess3.getErrorStream(), processOutput3);

        // we wait for the third TaskManager to register
        // since some of the CI environments are very hostile, we need to give this a lot of time (2 minutes)
        waitUntilNumTaskManagersAreRegistered(jmActor, 3, 120000);

        // kill one of the previous TaskManagers, triggering a failure and recovery
        taskManagerProcess1.destroy();
        taskManagerProcess1 = null;

        // we create the marker file which signals the program functions tasks that they can complete
        touchFile(new File(coordinateTempDir, PROCEED_MARKER_FILE));

        // wait for at most 5 minutes for the program to complete
        programTrigger.join(300000);

        // check that the program really finished
        assertFalse("The program did not finish in time", programTrigger.isAlive());

        // check whether the program encountered an error
        if (errorRef.get() != null) {
            Throwable error = errorRef.get();
            error.printStackTrace();
            fail("The program encountered a " + error.getClass().getSimpleName() + " : " + error.getMessage());
        }

        // all seems well :-)
    } catch (Exception e) {
        e.printStackTrace();
        printProcessLog("TaskManager 1", processOutput1.toString());
        printProcessLog("TaskManager 2", processOutput2.toString());
        printProcessLog("TaskManager 3", processOutput3.toString());
        fail(e.getMessage());
    } catch (Error e) {
        e.printStackTrace();
        printProcessLog("TaskManager 1", processOutput1.toString());
        printProcessLog("TaskManager 2", processOutput2.toString());
        printProcessLog("TaskManager 3", processOutput3.toString());
        throw e;
    } finally {
        if (taskManagerProcess1 != null) {
            taskManagerProcess1.destroy();
        }
        if (taskManagerProcess2 != null) {
            taskManagerProcess2.destroy();
        }
        if (taskManagerProcess3 != null) {
            taskManagerProcess3.destroy();
        }
        if (jmActorSystem != null) {
            jmActorSystem.shutdown();
        }
        if (coordinateTempDir != null) {
            try {
                FileUtils.deleteDirectory(coordinateTempDir);
            } catch (Throwable t) {
                // we can ignore this
            }
        }
    }
}

From source file:org.apache.nifi.processors.kite.InferAvroSchema.java

/**
 * Infers the Avro schema from the input Flowfile content.
 *
 * @param inputFlowFile// w w  w.  j a v  a  2 s.  c  o  m
 *  The original input FlowFile containing the JSON content as it entered this processor.
 *
 * @param context
 *  ProcessContext to pull processor configurations.
 *
 * @param session
 *  ProcessSession to transfer FlowFiles
 */
private String inferAvroSchemaFromJSON(final FlowFile inputFlowFile, final ProcessContext context,
        final ProcessSession session) {

    final AtomicReference<String> avroSchema = new AtomicReference<>();
    session.read(inputFlowFile, new InputStreamCallback() {
        @Override
        public void process(InputStream in) throws IOException {
            Schema as = JsonUtil.inferSchema(in,
                    context.getProperty(RECORD_NAME).evaluateAttributeExpressions(inputFlowFile).getValue(),
                    context.getProperty(NUM_RECORDS_TO_ANALYZE).evaluateAttributeExpressions(inputFlowFile)
                            .asInteger());
            avroSchema.set(as.toString(context.getProperty(PRETTY_AVRO_OUTPUT).asBoolean()));

        }
    });

    return avroSchema.get();
}

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

@Test
public void connectTimeout() throws Exception {
    // Pick a free port with no server running
    ServerSocket ss = new ServerSocket(0);
    int serverPort = ss.getLocalPort();
    ss.close();//from  w ww  .  j a va2  s.  c o m

    set(client + ".niws.client.ConnectTimeout", "100");
    int code = 200;
    statusCode.set(code);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> throwable = new AtomicReference<>();
    rxHttp.get("niws://test/http://localhost:" + serverPort + "/empty").subscribe(Actions.empty(),
            new Action1<Throwable>() {
                @Override
                public void call(Throwable t) {
                    throwable.set(t);
                    latch.countDown();
                }
            }, new Action0() {
                @Override
                public void call() {
                    latch.countDown();
                }
            });

    latch.await();
    Assert.assertTrue(throwable.get() instanceof ConnectException);
}

From source file:com.heliosdecompiler.helios.tasks.DecompileAndSaveTask.java

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Collections.singletonList("zip"));
    if (file == null)
        return;//from   ww  w  . j  av  a2  s .c o m
    if (file.exists()) {
        boolean delete = SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Overwrite existing file",
                "The selected file already exists. Overwrite?");
        if (!delete) {
            return;
        }
    }

    AtomicReference<Transformer> transformer = new AtomicReference<>();

    Display display = Display.getDefault();
    display.asyncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        FillLayout layout = new FillLayout();
        layout.type = SWT.VERTICAL;
        shell.setLayout(layout);
        Transformer.getAllTransformers(t -> {
            return t instanceof Decompiler || t instanceof Disassembler;
        }).forEach(t -> {
            Button button = new Button(shell, SWT.RADIO);
            button.setText(t.getName());
            button.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    transformer.set(t);
                }
            });
        });
        Button ok = new Button(shell, SWT.NONE);
        ok.setText("OK");
        ok.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.close();
                shell.dispose();
                synchronized (transformer) {
                    transformer.notify();
                }
            }
        });
        shell.pack();
        SWTUtil.center(shell);
        shell.open();
    });

    synchronized (transformer) {
        try {
            transformer.wait();
        } catch (InterruptedException e) {
            ExceptionHandler.handle(e);
        }
    }

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        file.createNewFile();
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        Set<String> written = new HashSet<>();
        for (Pair<String, String> pair : data) {
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getAllData().get(innerName);
                if (bytes != null) {
                    if (loadedFile.getClassNode(pair.getValue1()) != null) {
                        StringBuilder buffer = new StringBuilder();
                        transformer.get().transform(loadedFile.getClassNode(pair.getValue1()), bytes, buffer);
                        String name = innerName.substring(0, innerName.length() - 6) + ".java";
                        if (written.add(name)) {
                            zipOutputStream.putNextEntry(new ZipEntry(name));
                            zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + name);
                        }
                    } else {
                        if (written.add(pair.getValue1())) {
                            zipOutputStream.putNextEntry(new ZipEntry(pair.getValue1()));
                            zipOutputStream.write(loadedFile.getAllData().get(pair.getValue1()));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + pair.getValue1());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

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/*w  ww .j  a  v a  2s. 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:org.apache.hadoop.hdfs.TestMultiThreadedSync.java

/**
 * Test case where a bunch of threads are continuously calling sync() while another
 * thread appends some data and then closes the file.
 *
 * The syncing threads should eventually catch an IOException stating that the stream
 * was closed -- and not an NPE or anything like that.
 *///w w  w  .  j  a  va2s .co  m
@Test
public void testSyncWhileClosing() throws Throwable {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null);
    FileSystem fs = cluster.getFileSystem();
    Path p = new Path("/sync-and-close.dat");

    final FSDataOutputStream stm = createFile(fs, p, 1);

    ArrayList<Thread> flushers = new ArrayList<Thread>();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    try {
        for (int i = 0; i < 10; i++) {
            Thread flusher = new Thread() {
                public void run() {
                    try {
                        while (true) {
                            try {
                                stm.sync();
                            } catch (IOException ioe) {
                                if (!ioe.toString().contains("DFSOutputStream is closed")) {
                                    throw ioe;
                                } else {
                                    return;
                                }
                            }
                        }
                    } catch (Throwable t) {
                        thrown.set(t);
                    }
                }
            };
            flusher.start();
            flushers.add(flusher);
        }

        // Write some data
        for (int i = 0; i < 10000; i++) {
            stm.write(1);
        }

        // Close it while the flushing threads are still flushing
        stm.close();

        // Wait for the flushers to all die.
        for (Thread t : flushers) {
            t.join();
        }

        // They should have all gotten the expected exception, not anything
        // else.
        if (thrown.get() != null) {
            throw thrown.get();
        }

    } finally {
        fs.close();
        cluster.shutdown();
    }
}

From source file:org.apache.solr.common.util.TestJsonRecordReader.java

License:asdf

public void testArrayOfRootObjects() throws Exception {
    String json = "[{'fieldA':'A1'}, {'fieldB':'B2'}]";
    JsonRecordReader streamer;//from  w  w w  .  jav a  2  s  .c om
    List<Map<String, Object>> records;

    final AtomicReference<WeakReference<String>> ref = new AtomicReference<>();
    streamer = JsonRecordReader.getInst("/", Collections.singletonList("$FQN:/**"));
    streamer.streamRecords(new StringReader(json), (record, path) -> {
        System.gc();
        if (ref.get() != null) {
            assertNull("This reference is still intact :" + ref.get().get(), ref.get().get());
        }
        String fName = record.keySet().iterator().next();
        ref.set(new WeakReference<>(fName));
    });

}