Java Code Examples for java.util.concurrent.atomic.AtomicReference.get()

The following are Jave code examples for showing how to use get() of the java.util.concurrent.atomic.AtomicReference class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: validator-web   File: AbstractJackson2HttpMessageReader.java   Source Code and License Vote up 6 votes
@Override
protected boolean supports(Class<?> clazz) {
    JavaType javaType = getJavaType(clazz);
    AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    if (this.objectMapper.canDeserialize(javaType, causeRef)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        String msg = "Failed to evaluate deserialization for type " + javaType;
        if (logger.isDebugEnabled()) {
            logger.warn(msg, cause);
        }
        else {
            logger.warn(msg + ": " + cause);
        }
    }
    return false;
}
 
Example 2
Project: util   File: ConcurrentHashMapV8.java   Source Code and License Vote up 6 votes
public final void compute() {
	final Fun<Entry<K, V>, ? extends U> searchFunction;
	final AtomicReference<U> result;
	if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) {
		for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) {
			if (result.get() != null)
				return;
			addToPendingCount(1);
			new SearchEntriesTask<K, V, U>(this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result)
					.fork();
		}
		while (result.get() == null) {
			U u;
			Node<K, V> p;
			if ((p = advance()) == null) {
				propagateCompletion();
				break;
			}
			if ((u = searchFunction.apply(p)) != null) {
				if (result.compareAndSet(null, u))
					quietlyCompleteRoot();
				return;
			}
		}
	}
}
 
Example 3
Project: openjdk-jdk10   File: CTrayIcon.java   Source Code and License Vote up 6 votes
private void showMessageDialog() {

        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        AtomicReference<Point2D> ref = new AtomicReference<>();
        execute(ptr -> {
            ref.set(nativeGetIconLocation(ptr));
        });
        Point2D iconLoc = ref.get();
        if (iconLoc == null) {
            return;
        }

        int dialogY = (int)iconLoc.getY();
        int dialogX = (int)iconLoc.getX();
        if (dialogX + messageDialog.getWidth() > screenSize.width) {
            dialogX = screenSize.width - messageDialog.getWidth();
        }

        messageDialog.setLocation(dialogX, dialogY);
        messageDialog.setVisible(true);
    }
 
Example 4
Project: n4js   File: ExternalProject.java   Source Code and License Vote up 6 votes
private <T extends IResource> T getResource(String name, Class<T> resourceClass) {
	final File fileCandidate = getFullPath().append(name).toFile();
	final AtomicReference<T> actualRef = new AtomicReference<>();
	if (fileCandidate.exists()) {
		acceptUnsafe(resource -> {
			if (resource instanceof IExternalResource && resourceClass.isAssignableFrom(resource.getClass())) {
				if (fileCandidate.equals(((IExternalResource) resource).getExternalResource())) {
					actualRef.set(resourceClass.cast(resource));
					return false;
				}
			}
			return true;
		});
	}

	return actualRef.get(); // TODO return with missing instance?
}
 
Example 5
Project: elasticsearch_my   File: HeapBufferedAsyncResponseConsumerTests.java   Source Code and License Vote up 6 votes
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    consumer.onResponseReceived(new BasicHttpResponse(statusLine));

    final AtomicReference<Long> contentLength = new AtomicReference<>();
    HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) {
        @Override
        public long getContentLength() {
            return contentLength.get();
        }
    };
    contentLength.set(randomLong(bufferLimit));
    consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);

    contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE));
    try {
        consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
    } catch(ContentTooLongException e) {
        assertEquals("entity content is too long [" + entity.getContentLength() +
                "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage());
    }
}
 
Example 6
Project: Biliomi   File: SortDirectiveQueryProcessor.java   Source Code and License Vote up 6 votes
public static <T> Comparator<T> buildComparatorChain(Collection<RestSortDirective> sortDirectives, Class<T> rootClass) {
  AtomicReference<Comparator<T>> comparatorChainRef = new AtomicReference<>();

  if (sortDirectives != null && sortDirectives.size() > 0) {

    sortDirectives.forEach(sortDirective -> {
      Comparator<T> comparator = XmlElementPathBeanComparator.forSortDirective(sortDirective, rootClass);

      if (comparatorChainRef.get() == null) {
        comparatorChainRef.set(comparator);
      } else {
        comparatorChainRef.updateAndGet(p -> p.thenComparing(comparator));
      }
    });

  }
  return comparatorChainRef.get();
}
 
Example 7
Project: java-coap   File: TransactionManager.java   Source Code and License Vote up 6 votes
public Optional<CoapTransaction> findMatchAndRemoveForSeparateResponse(CoapPacket req) {
    if ((req.getMessageType() == MessageType.Confirmable || req.getMessageType() == MessageType.NonConfirmable)
            && req.getCode() != null && req.getToken().length > 0) {

        AtomicReference<Optional<CoapTransaction>> transactionFound = new AtomicReference<>(Optional.empty());

        transactionQueues.computeIfPresent(req.getRemoteAddress(), (address, coapTransactions) -> {
            QueueUpdateResult result = coapTransactions.findAndRemoveSeparateResponse(req);

            transactionFound.set(result.coapTransaction);
            return result.transactionQueue;
        });

        return transactionFound.get();
    } else {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("findMatchAndRemoveForSeparateResponse(" + req.toString(false) + "): not found");
        }
        return Optional.empty();
    }
}
 
Example 8
Project: jsf-sdk   File: ReferenceCodec.java   Source Code and License Vote up 5 votes
@SuppressWarnings("rawtypes")
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    Object item;
    if (object instanceof AtomicReference) {
        AtomicReference val = (AtomicReference) object;
        item = val.get();
    } else {
        item = ((Reference) object).get();
    }
    serializer.write(item);
}
 
Example 9
Project: n4js   File: ChooseImplementationHelper.java   Source Code and License Vote up 5 votes
/***
 * Choose an implementation if needed
 *
 * @param runnerId
 *            the runner ID, e.g. NODEJS
 * @param moduleToRun
 *            the emf-full URI to the module to run
 * @return the selected implementation Id
 */
public String chooseImplementationIfRequired(String runnerId, URI moduleToRun) {
	// first see if we need to supply an implementationId
	// (we need one if there are API projects among the dependencies of the moduleToRun AND there exist 2 or more
	// implementations for them)
	final ApiUsage apiUsage = runnerHelper.getProjectExtendedDeps(runnerId, moduleToRun);
	final ApiImplMapping apiImplMapping = apiUsage.apiImplMapping;

	final List<String> availableImplIds = apiImplMapping.getAllImplIds();
	if (apiImplMapping.isEmpty())
		return null; // no API projects among the dependencies -> no need to bother the user
	if (availableImplIds.isEmpty())
		return null; // no implementations available -> error will be shown somewhere else
	if (availableImplIds.size() == 1)
		return availableImplIds.get(0); // exactly 1 implementation -> use that, no need to bother the user
	// make user choose:
	// We have to open the dialog on the UI-thread
	// See:
	// http://stackoverflow.com/questions/354796/whats-the-best-way-to-get-a-return-value-out-of-an-asyncexec-in-eclipse
	final AtomicReference<String> result = new AtomicReference<>();
	final ChooseImplementationDialog dlg = new ChooseImplementationDialog(null, apiImplMapping);
	Display.getDefault().syncExec(new Runnable() {
		@Override
		public void run() {
			if (dlg.open() == Window.OK) {
				result.set((String) dlg.getResult()[0]);
			} else {
				result.set(CANCEL);
			}
		}
	});

	return result.get();
}
 
Example 10
Project: n4js   File: ContentAssistXpectMethod.java   Source Code and License Vote up 5 votes
private ICompletionProposal[] allProposalsAt(RegionWithCursor offset, N4ContentAssistProcessorTestBuilder fixture) {
	AtomicReference<ICompletionProposal[]> w = new AtomicReference<>();

	Display.getDefault().syncExec(() -> {

		try {
			w.set(fixture.computeCompletionProposals(offset
					.getGlobalCursorOffset()));
		} catch (Exception e) {
			logger.warn("Cannot compute Completion Proposals", e);
		}
	});

	return w.get();
}
 
Example 11
Project: kafka-0.11.0.0-src-with-comment   File: WorkerGroupMember.java   Source Code and License Vote up 5 votes
private void stop(boolean swallowException) {
    log.trace("Stopping the Connect group member.");
    AtomicReference<Throwable> firstException = new AtomicReference<Throwable>();
    this.stopped = true;
    ClientUtils.closeQuietly(coordinator, "coordinator", firstException);
    ClientUtils.closeQuietly(metrics, "consumer metrics", firstException);
    ClientUtils.closeQuietly(client, "consumer network client", firstException);
    AppInfoParser.unregisterAppInfo(JMX_PREFIX, clientId);
    if (firstException.get() != null && !swallowException)
        throw new KafkaException("Failed to stop the Connect group member", firstException.get());
    else
        log.debug("The Connect group member has stopped.");
}
 
Example 12
Project: android-retroatomic   File: Phaser.java   Source Code and License Vote up 5 votes
/**
 * Removes and signals threads from queue for phase.
 */
private void releaseWaiters(int phase) {
    QNode q;   // first element of queue
    Thread t;  // its thread
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    while ((q = head.get()) != null &&
           q.phase != (int) (root.state >>> PHASE_SHIFT)) {
        if (head.compareAndSet(q, q.next) &&
            (t = q.thread) != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 13
Project: openjdk-jdk10   File: GetMousePositionWithOverlay.java   Source Code and License Vote up 5 votes
private static Point getMousePosition(final Component component) throws Exception {
    final AtomicReference<Point> pos = new AtomicReference<Point>();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            pos.set(component.getMousePosition());
        }
    });
    return pos.get();
}
 
Example 14
Project: athena   File: ECDeviceStore.java   Source Code and License Vote up 5 votes
private DeviceEvent refreshDeviceCache(ProviderId providerId, DeviceId deviceId) {
    AtomicReference<DeviceEvent.Type> eventType = new AtomicReference<>();
    Device device = devices.compute(deviceId, (k, existingDevice) -> {
        Device newDevice = composeDevice(deviceId);
        if (existingDevice == null) {
            eventType.set(DEVICE_ADDED);
        } else {
            // We allow only certain attributes to trigger update
            boolean propertiesChanged =
                    !Objects.equals(existingDevice.hwVersion(), newDevice.hwVersion()) ||
                            !Objects.equals(existingDevice.swVersion(), newDevice.swVersion()) ||
                            !Objects.equals(existingDevice.providerId(), newDevice.providerId());
            boolean annotationsChanged =
                    !AnnotationsUtil.isEqual(existingDevice.annotations(), newDevice.annotations());

            // Primary providers can respond to all changes, but ancillary ones
            // should respond only to annotation changes.
            if ((providerId.isAncillary() && annotationsChanged) ||
                    (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
                boolean replaced = devices.replace(deviceId, existingDevice, newDevice);
                verify(replaced, "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
                        providerId, existingDevice, devices.get(deviceId), newDevice);
                eventType.set(DEVICE_UPDATED);
            }
        }
        return newDevice;
    });
    if (eventType.get() != null && !providerId.isAncillary()) {
        markOnline(deviceId);
    }
    return eventType.get() != null ? new DeviceEvent(eventType.get(), device) : null;
}
 
Example 15
Project: boohee_v5.6   File: RefCountSubscription.java   Source Code and License Vote up 5 votes
public void unsubscribe() {
    State newState;
    AtomicReference<State> localState = this.state;
    State oldState;
    do {
        oldState = (State) localState.get();
        if (!oldState.isUnsubscribed) {
            newState = oldState.unsubscribe();
        } else {
            return;
        }
    } while (!localState.compareAndSet(oldState, newState));
    unsubscribeActualIfApplicable(newState);
}
 
Example 16
Project: OpenJSharp   File: Phaser.java   Source Code and License Vote up 5 votes
/**
 * Variant of releaseWaiters that additionally tries to remove any
 * nodes no longer waiting for advance due to timeout or
 * interrupt. Currently, nodes are removed only if they are at
 * head of queue, which suffices to reduce memory footprint in
 * most usages.
 *
 * @return current phase on exit
 */
private int abortWait(int phase) {
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    for (;;) {
        Thread t;
        QNode q = head.get();
        int p = (int)(root.state >>> PHASE_SHIFT);
        if (q == null || ((t = q.thread) != null && q.phase == p))
            return p;
        if (head.compareAndSet(q, q.next) && t != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 17
Project: java-red   File: TestRedFuture.java   Source Code and License Vote up 5 votes
/**
 * Tests failed {@link RedFutureOf} callbacks on current thread.
 */
@Test
public void testFutureOfFailureOnCurrentThread() throws Throwable {
    CountDownLatch lock = new CountDownLatch(2);
    AtomicReference<Throwable> failure = new AtomicReference<>();
    long time = System.currentTimeMillis();
    RedFutureOf<Object> future = failingFutureOf(new TestException());
    future.addFailureCallback(throwable -> {
        if (!(throwable instanceof TestException)) {
            failure.compareAndSet(null, throwable);
        }
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("success too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("success block on unexpected thread"));
        }
        lock.countDown();
    });
    future.addFinallyCallback(() -> {
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("finally too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("finally block on unexpected thread"));
        }
        lock.countDown();
    });
    future.addSuccessCallback(() ->
            failure.compareAndSet(null, new RuntimeException("should not have reached success block")));
    future.addSuccessCallback(o ->
            failure.compareAndSet(null, new RuntimeException("should not have reached result success block")));
    lock.await(300, TimeUnit.MILLISECONDS);
    Thread.sleep(VALIDATION_SLEEP_TIME);
    if (failure.get() != null) {
        throw failure.get();
    }
}
 
Example 18
Project: elasticsearch_my   File: UnicastZenPingTests.java   Source Code and License Vote up 5 votes
PingCollection pingAndWait() throws ExecutionException, InterruptedException {
    allTasksCompleted = new CountDownLatch(1);
    pingingRoundClosed = new CountDownLatch(1);
    pendingTasks = new AtomicInteger();
    // mark the three sending rounds as ongoing
    markTaskAsStarted("send pings");
    markTaskAsStarted("send pings");
    markTaskAsStarted("send pings");
    final AtomicReference<PingCollection> response = new AtomicReference<>();
    ping(response::set, TimeValue.timeValueMillis(1), TimeValue.timeValueSeconds(1));
    pingingRoundClosed.await();
    final PingCollection result = response.get();
    assertNotNull("pinging didn't complete",  result);
    return result;
}
 
Example 19
Project: jdk8u-jdk   File: ConcurrentHashMap.java   Source Code and License Vote up 5 votes
public final void compute() {
    final BiFunction<? super K, ? super V, ? extends U> searchFunction;
    final AtomicReference<U> result;
    if ((searchFunction = this.searchFunction) != null &&
        (result = this.result) != null) {
        for (int i = baseIndex, f, h; batch > 0 &&
                 (h = ((f = baseLimit) + i) >>> 1) > i;) {
            if (result.get() != null)
                return;
            addToPendingCount(1);
            new SearchMappingsTask<K,V,U>
                (this, batch >>>= 1, baseLimit = h, f, tab,
                 searchFunction, result).fork();
        }
        while (result.get() == null) {
            U u;
            Node<K,V> p;
            if ((p = advance()) == null) {
                propagateCompletion();
                break;
            }
            if ((u = searchFunction.apply(p.key, p.val)) != null) {
                if (result.compareAndSet(null, u))
                    quietlyCompleteRoot();
                break;
            }
        }
    }
}
 
Example 20
Project: java-red   File: TestRedFuture.java   Source Code and License Vote up 4 votes
/**
 * Tests successfully following {@link RedFutureOf} callbacks on current thread.
 */
@Test
public void testFutureOfFollowSuccessOnCurrentThread() throws Throwable {
    CountDownLatch lock = new CountDownLatch(3);
    AtomicReference<Throwable> failure = new AtomicReference<>();
    long time = System.currentTimeMillis();
    Object object = new Object();
    OpenRedFutureOf<Object> future = RedFuture.futureOf();
    future.follow(successfulFutureOf(object));
    future.addFailureCallback(throwable -> failure.compareAndSet(null, throwable));
    future.addSuccessCallback(() -> {
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("success too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("success block on unexpected thread"));
        }
        lock.countDown();
    });
    future.addSuccessCallback(o -> {
        if (o != object) {
            failure.compareAndSet(null, new RuntimeException("unexpected future value"));
        }
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("success too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("success block on unexpected thread"));
        }
        lock.countDown();
    });
    future.addFinallyCallback(() -> {
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("finally too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("finally block on unexpected thread"));
        }
        lock.countDown();
    });
    lock.await(300, TimeUnit.MILLISECONDS);
    Thread.sleep(VALIDATION_SLEEP_TIME);
    if (failure.get() != null) {
        throw failure.get();
    }
}