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.facebook.RequestTests.java

@LargeTest
public void testUploadVideoFileToUserId() throws IOException, URISyntaxException {
    File tempFile = null;/*  ww w . j  av a  2 s . c o m*/
    try {
        GraphRequest meRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), null);
        GraphResponse meResponse = meRequest.executeAndWait();
        JSONObject meJson = meResponse.getJSONObject();
        assertNotNull(meJson);

        String userId = meJson.optString("id");
        assertNotNull(userId);

        tempFile = createTempFileFromAsset("DarkScreen.mov");
        ShareVideo video = new ShareVideo.Builder().setLocalUrl(Uri.fromFile(tempFile)).build();
        ShareVideoContent content = new ShareVideoContent.Builder().setVideo(video).build();
        final ShareApi shareApi = new ShareApi(content);
        shareApi.setGraphNode(userId);
        final AtomicReference<String> videoId = new AtomicReference<>(null);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shareApi.share(new FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        videoId.set(result.getPostId());
                        notifyShareFinished();
                    }

                    @Override
                    public void onCancel() {
                        notifyShareFinished();
                    }

                    @Override
                    public void onError(FacebookException error) {
                        notifyShareFinished();
                    }

                    private void notifyShareFinished() {
                        synchronized (shareApi) {
                            shareApi.notifyAll();
                        }
                    }
                });
            }
        });

        synchronized (shareApi) {
            shareApi.wait(REQUEST_TIMEOUT_MILLIS);
        }
        assertNotNull(videoId.get());
    } catch (Exception ex) {
        fail();
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java

@Test
public void shouldReloadClassLoaderWhileDoingEvalInSeparateThread() throws Exception {
    final AtomicBoolean fail = new AtomicBoolean(false);
    final AtomicInteger counter = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Color> color = new AtomicReference<>(Color.RED);

    final GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine();

    try {//  ww w.  j  a  v a  2 s.c o m
        scriptEngine.eval("Color.BLACK");
        fail("Should fail as class is not yet imported");
    } catch (ScriptException se) {
        // should get here as Color.BLACK is not imported yet.
        logger.info("Failed to execute Color.BLACK as expected.");
    }

    final Thread evalThread = new Thread(() -> {
        try {
            // execute scripts until the other thread releases this latch (i.e. after import)
            while (latch.getCount() == 1) {
                scriptEngine.eval("1+1");
                counter.incrementAndGet();
            }

            color.set((Color) scriptEngine.eval("Color.BLACK"));
        } catch (Exception se) {
            fail.set(true);
        }
    }, "test-reload-classloader-1");

    evalThread.start();

    // let the first thread execute a bit.
    Thread.sleep(1000);

    final Thread importThread = new Thread(() -> {
        logger.info("Importing java.awt.Color...");
        final Set<String> imports = new HashSet<String>() {
            {
                add("import java.awt.Color");
            }
        };
        scriptEngine.addImports(imports);
        latch.countDown();
    }, "test-reload-classloader-2");

    importThread.start();

    // block until both threads are done
    importThread.join();
    evalThread.join();

    assertEquals(Color.BLACK, color.get());
    assertThat(counter.get(), greaterThan(0));
    assertFalse(fail.get());
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClientTests.java

public void testThatHttpClientFailsOnNonHttpResponse() throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    AtomicReference<Exception> hasExceptionHappened = new AtomicReference();
    try (ServerSocket serverSocket = new MockServerSocket(0, 50, InetAddress.getByName("localhost"))) {
        executor.execute(() -> {//from  ww w  .ja v  a  2s . c  o m
            try (Socket socket = serverSocket.accept()) {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                in.readLine();
                socket.getOutputStream().write("This is not a HTTP response".getBytes(StandardCharsets.UTF_8));
                socket.getOutputStream().flush();
            } catch (Exception e) {
                hasExceptionHappened.set(e);
                logger.error((Supplier<?>) () -> new ParameterizedMessage("Error in writing non HTTP response"),
                        e);
            }
        });
        HttpRequest request = HttpRequest.builder("localhost", serverSocket.getLocalPort()).path("/").build();
        expectThrows(ClientProtocolException.class, () -> httpClient.execute(request));
        assertThat("A server side exception occured, but shouldn't", hasExceptionHappened.get(),
                is(nullValue()));
    } finally {
        terminate(executor);
    }
}

From source file:de.hybris.platform.test.HJMPOptimisticConcurrencyPerformanceTest.java

private Thread[] createTxThreads(final TxRunnable tx1Runnable, final TxRunnable tx2Runnable,
        final AtomicReference<Throwable> tx1Error, final AtomicReference<Throwable> tx2Error) {
    final CountDownLatch afterTx1Write = new CountDownLatch(1);
    final Tenant t = Registry.getCurrentTenantNoFallback();

    final Thread tx1Thread = new Thread() {
        @Override/*from w  ww . j  a  v  a  2 s  .  co m*/
        public void run() {
            Registry.setCurrentTenant(t);
            try {
                // this tx flush its changes and signals write via CountDownLatch
                final Transaction tx = new TestTransaction(afterTx1Write, false);
                tx.activateAsCurrentTransaction();
                tx.execute(new TransactionBody() {
                    @Override
                    public Object execute() throws Exception {
                        prepareTransaction(tx);
                        tx1Runnable.run();
                        return null;
                    }
                });
            } catch (final Throwable e) {
                tx1Error.set(e);
            }
        }
    };
    final Thread tx2Thread = new Thread() {
        @Override
        public void run() {
            Registry.setCurrentTenant(t);
            try {
                // this tx does wait for other tx to flush its changes to ensure conflict here
                final Transaction tx = new TestTransaction(afterTx1Write, true);
                tx.activateAsCurrentTransaction();
                tx.execute(new TransactionBody() {
                    @Override
                    public Object execute() throws Exception {
                        prepareTransaction(tx);
                        tx2Runnable.run();
                        return null;
                    }
                });
            } catch (final Exception e) {
                tx2Error.set(e);
            }
        }
    };
    return new Thread[] { tx1Thread, tx2Thread };
}

From source file:org.apache.openejb.activemq.JMS2AMQTest.java

@Test
public void receiveGetBody() throws InterruptedException {
    final String text = TEXT + "2";
    final AtomicReference<Throwable> error = new AtomicReference<>();
    final CountDownLatch ready = new CountDownLatch(1);
    final CountDownLatch over = new CountDownLatch(1);
    new Thread() {
        @Override/*w ww .j  a v  a  2  s  . c o m*/
        public void run() {
            {
                setName(JMS2AMQTest.class.getName() + ".receiveGetBody#receiver");
            }

            try (final JMSContext context = cf.createContext()) {
                try (final JMSConsumer consumer = context.createConsumer(destination2)) {
                    ready.countDown();
                    final Message receive = consumer.receive(TimeUnit.MINUTES.toMillis(1));
                    assertEquals(text, receive.getBody(String.class));
                }
            } catch (final Throwable ex) {
                error.set(ex);
            } finally {
                over.countDown();
            }
        }
    }.start();

    ready.await(1, TimeUnit.MINUTES);
    sleep(150); // just to ensure we called receive already

    // now send the message
    try (final JMSContext context = cf.createContext()) {
        context.createProducer().send(destination2, text);
    } catch (final JMSRuntimeException ex) {
        fail(ex.getMessage());
    }

    over.await(1, TimeUnit.MINUTES);

    // ensure we got the message and no exception
    final Throwable exception = error.get();
    if (exception != null) {
        exception.printStackTrace();
    }
    assertNull(exception == null ? "ok" : exception.getMessage(), exception);
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoClassGenerator.java

@Override
public void generateType(PojoCodeGenerationContext context, SchemaTree schema, JavaWriter writer)
        throws IOException, CodeGenerationException {
    Mapping mapping = context.getMapping();

    // Process the properties into PropertyGenerators
    List<PojoPropertyGenerator> propertyGenerators = new ArrayList<>();

    visitProperties(schema, new PropertyVisitor<CodeGenerationException>() {
        @Override//  w  w w  . j a  v  a 2s.co  m
        public void visitProperty(String propertyName, URI type, SchemaTree schema)
                throws CodeGenerationException {
            String defaultValue;
            JsonNode defaultValueNode = schema.getNode().path("default");
            if (defaultValueNode.isMissingNode() || defaultValueNode.isNull()) {
                defaultValue = null;
            } else if (defaultValueNode.isTextual()) {
                defaultValue = '"' + defaultValueNode.textValue() + '"';
            } else {
                defaultValue = defaultValueNode.asText();
            }

            PojoPropertyGenerator propertyGenerator = context.createPropertyGenerator(type, propertyName,
                    defaultValue);
            propertyGenerators.add(propertyGenerator);
        }

        @Override
        public void visitProperty(String propertyName, URI type) throws CodeGenerationException {
            propertyGenerators.add(context.createPropertyGenerator(type, propertyName, null));
        }
    });

    for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
        propertyGenerator.generateImports(writer);
    }

    // check whether we need to work with additionalProperties:
    // - schema can say "yes", or "yes-with-this-type"
    // - mapping can say "yes", or "ignore"
    // Ultimately if we have to handle them we let the generated class extend AbstractMap<String, TYPE>,
    // where TYPE is either the one from the schema, or Object (if the schema didn't specify anything.
    // XXX: "Object" should probably be "whatever our factory/reader would produce"
    // XXX: Instead an AbstractMap, should we have a standard class in our support library?
    ClassName additionalPropertiesValueClassName = null;
    ClassName extendedClass = mapping.getExtends();
    JsonNode additionalPropertiesNode = schema.getNode().path("additionalProperties");
    if (!additionalPropertiesNode.isMissingNode() && !additionalPropertiesNode.isNull()
            && !mapping.isIgnoreAdditionalProperties()) {
        if (additionalPropertiesNode.isBoolean()) {
            if (additionalPropertiesNode.booleanValue()) {
                additionalPropertiesValueClassName = ClassName.create(Object.class);
            }
        } else {
            assert additionalPropertiesNode.isContainerNode();

            AtomicReference<ClassName> ref = new AtomicReference<>();
            SchemaTree additionalPropertiesSchema = schema.append(JsonPointer.of("additionalProperties"));
            URI additionalPropertiesUri = additionalPropertiesSchema.getLoadingRef().toURI()
                    .resolve("#" + additionalPropertiesSchema.getPointer().toString());
            visitSchema(additionalPropertiesUri, additionalPropertiesSchema,
                    new SchemaVisitor<CodeGenerationException>() {
                        @Override
                        public void visitSchema(URI type, SchemaTree schema) throws CodeGenerationException {
                            visitSchema(type);
                        }

                        @Override
                        public void visitSchema(URI type) throws CodeGenerationException {
                            ref.set(context.getGenerator().generate(type));
                        }
                    });
            additionalPropertiesValueClassName = ref.get();
        }

        if (additionalPropertiesValueClassName != null) {
            if (extendedClass != null) {
                // FIXME: handle this by using an interface instead
                throw new CodeGenerationException(context.getType(),
                        "additionalProperties is incompatible with 'extends'");
            }
            extendedClass = ClassName.create(AbstractMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(extendedClass);
            ClassName mapClass = ClassName.create(Map.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(mapClass);
            ClassName hashMapClass = ClassName.create(HashMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(hashMapClass);
            ClassName mapEntryClass = ClassName.create(Map.Entry.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(mapEntryClass);
            ClassName setMapEntryClass = ClassName.create(Set.class, mapEntryClass);
            writer.writeImport(setMapEntryClass);
        }
    }

    if (mapping.getImplements() != null) {
        for (ClassName implementedInterface : mapping.getImplements()) {
            writer.writeImport(implementedInterface);
        }
    }

    writeSchemaDocumentation(schema, writer);
    writer.writeClassStart(mapping.getGeneratedClassName(), extendedClass, mapping.getImplements(), Kind.CLASS,
            Visibility.PUBLIC, mapping.getModifiers());
    try {
        // Write properties
        for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
            propertyGenerator.generateFields(writer);
        }
        if (additionalPropertiesValueClassName != null) {
            ClassName mapClass = ClassName.create(Map.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            ClassName hashMapClass = ClassName.create(HashMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeField(Visibility.PRIVATE, mapClass, "additionalPropertiesMap", () -> {
                writer.write(" = new ");
                // XXX: If code generation would know about java 7/8, we could use diamond here
                writer.writeClassName(hashMapClass);
                writer.write("()");
            });
        }

        // Write accessors
        // TODO: style to create them: pairs, or ordered?
        // TODO: whether to generate setters in the first place, or just getters
        for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
            propertyGenerator.generateGetter(writer);
            propertyGenerator.generateSetter(writer);
        }

        if (additionalPropertiesValueClassName != null) {
            ClassName mapEntryClass = ClassName.create(Map.Entry.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            ClassName setMapEntryClass = ClassName.create(Set.class, mapEntryClass);
            writer.writeAnnotation(ClassName.create(Override.class));
            writer.writeMethodBodyStart(Visibility.PUBLIC, setMapEntryClass, "entrySet");
            writer.writeCode("return additionalPropertiesMap.entrySet();");
            writer.writeMethodBodyEnd();
        }
    } finally {
        writer.writeClassEnd();
    }
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void rootServletContextResource() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    final AtomicReference<URL> rootResource = new AtomicReference<>();
    this.webServer = factory.getWebServer((servletContext) -> {
        try {/*  w w w.  ja  v a  2 s.  c o  m*/
            rootResource.set(servletContext.getResource("/"));
        } catch (MalformedURLException ex) {
            throw new ServletException(ex);
        }
    });
    this.webServer.start();
    assertThat(rootResource.get()).isNotNull();
}

From source file:byps.test.TestRemoteServerR.java

private void internalCallClientAsync(ServerIFAsync remote, int value, final AtomicInteger r1,
        final AtomicReference<Throwable> ex, final CountDownLatch countDown) {
    remote.callClientIncrementInt(value, new BAsyncResult<Integer>() {
        public void setAsyncResult(Integer result, Throwable exception) {
            if (exception != null) {
                ex.set(exception);
            } else {
                r1.set(result);//from  www.j a  v a 2  s. c o m
            }
            countDown.countDown();
        }
    });
}

From source file:net.ben.subsonic.androidapp.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;/*from   w  w w. j ava2 s.  c o  m*/
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testShareOpenGraphContentWithBadType() throws Exception {
    ShareOpenGraphObject ogObject = new ShareOpenGraphObject.Builder().putString("og:title", "a title")
            .putString("og:type", TEST_OG_OBJECT_TYPE).putString("og:description", "a description").build();

    ShareOpenGraphAction ogAction = new ShareOpenGraphAction.Builder()
            .setActionType(TEST_OG_ACTION_TYPE + "bad").putObject("test", ogObject).build();

    ShareOpenGraphContent content = new ShareOpenGraphContent.Builder().setAction(ogAction)
            .setPreviewPropertyName("test").build();

    final ShareApi shareApi = new ShareApi(content);
    final AtomicReference<String> actionId = new AtomicReference<>(null);
    final AtomicBoolean errorOccurred = new AtomicBoolean(false);

    getActivity().runOnUiThread(new Runnable() {
        @Override/*from ww w  .java  2s.co m*/
        public void run() {
            shareApi.share(new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    actionId.set(result.getPostId());
                    notifyShareFinished();
                }

                @Override
                public void onCancel() {
                    notifyShareFinished();
                }

                @Override
                public void onError(FacebookException error) {
                    errorOccurred.set(true);
                    notifyShareFinished();
                }

                private void notifyShareFinished() {
                    synchronized (shareApi) {
                        shareApi.notifyAll();
                    }
                }
            });
        }
    });

    synchronized (shareApi) {
        shareApi.wait(REQUEST_TIMEOUT_MILLIS);
    }
    assertNull(actionId.get());
    assertTrue(errorOccurred.get());
}