下面列出了java.util.concurrent.atomic.AtomicReference#getAndSet() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Configure {@link AutomatedActions}
*
* <p>Sets or updates a reference to automated actions.
*
* @param automated_actions {@link AutomatedActions} to configure
* @param item Item on which the actions should operate
* @param initial_severity Initial alarm severity (which is ignored)
* @param enabled Is the alarm enabled?
* @param actions Actions to execute
*/
public static void configure(final AtomicReference<AutomatedActions> automated_actions,
final AlarmTreeItem<?> item,
final SeverityLevel initial_severity,
final boolean enabled,
final List<TitleDetailDelay> actions)
{
// Update Automated Actions since their configuration changed
final AutomatedActions new_actions =
(actions.isEmpty() || !enabled)
? null
: new AutomatedActions(item, initial_severity, AutomatedActionExecutor.INSTANCE);
// Cancel previous ones.
final AutomatedActions previous = automated_actions.getAndSet(new_actions);
if (previous != null)
previous.cancel();
}
/**
* Create a wrapper Consumer, which will "debounce" i.e. postpone the function execution until after <code>period</code>
* has elapsed since last time it was invoked. <code>delegate</code> will be called most once <code>period</code>.
*
* @param delegate delegate consumer to be wrapped
* @param period given time period
* @param timeUnit unit of the period
* @return wrapped runnable
*/
public <T> Consumer<T> debounce(Consumer<T> delegate,
long period,
TimeUnit timeUnit) {
AtomicReference<ScheduledFuture<T>> reg = new AtomicReference<>();
return new Consumer<T>() {
@Override
public void accept(T t) {
ScheduledFuture<T> future = reg.getAndSet(scheduleOneShot(TimeUnit.NANOSECONDS.convert(period, timeUnit),
new Callable<T>() {
@Override
public T call() throws Exception {
delegate.accept(t);
return t;
}
}));
if (future != null) {
future.cancel(true);
}
}
};
}
@Test
public void rootChangeUnregistersFromPreviousChildAdapterIfExpanded() {
FakeAdapter rootAdapter = new FakeAdapter(1);
PowerAdapter oldChildAdapter = mock(PowerAdapter.class);
final AtomicReference<PowerAdapter> childAdapterRef = new AtomicReference<>(oldChildAdapter);
TreeAdapter treeAdapter = new TreeAdapter(rootAdapter, new ChildAdapterSupplier() {
@NonNull
@Override
public PowerAdapter get(int position) {
return childAdapterRef.get();
}
});
treeAdapter.setAutoExpand(true);
treeAdapter.registerDataObserver(mObserver);
// Set to return a different child adapter now.
childAdapterRef.getAndSet(EMPTY);
rootAdapter.change(0, 1, null);
// Verify that the same registered observer was later unregistered.
ArgumentCaptor<DataObserver> captor = ArgumentCaptor.forClass(DataObserver.class);
verify(oldChildAdapter).registerDataObserver(captor.capture());
verify(oldChildAdapter).unregisterDataObserver(eq(captor.getValue()));
}
@Test
public void executeJavaScript_delegatesToExecJs() {
AtomicReference<String> invokedExpression = new AtomicReference<>();
AtomicReference<Serializable[]> invokedParams = new AtomicReference<>();
Element element = new Element("div") {
@Override
public PendingJavaScriptResult executeJs(String expression,
Serializable... parameters) {
String oldExpression = invokedExpression.getAndSet(expression);
Assert.assertNull("There should be no old expression",
oldExpression);
Serializable[] oldParams = invokedParams.getAndSet(parameters);
Assert.assertNull("There should be no old params", oldParams);
return null;
}
};
element.executeJavaScript("foo", 1, true);
Assert.assertEquals("foo", invokedExpression.get());
Assert.assertEquals(Integer.valueOf(1), invokedParams.get()[0]);
Assert.assertEquals(Boolean.TRUE, invokedParams.get()[1]);
}
@Test
public void callFunction_delegatesToCallJsFunction() {
AtomicReference<String> invokedFuction = new AtomicReference<>();
AtomicReference<Serializable[]> invokedParams = new AtomicReference<>();
Element element = new Element("div") {
@Override
public PendingJavaScriptResult callJsFunction(String functionName,
Serializable... arguments) {
String oldExpression = invokedFuction.getAndSet(functionName);
Assert.assertNull("There should be no old function name",
oldExpression);
Serializable[] oldParams = invokedParams.getAndSet(arguments);
Assert.assertNull("There should be no old params", oldParams);
return null;
}
};
element.callFunction("foo", 1, true);
Assert.assertEquals("foo", invokedFuction.get());
Assert.assertEquals(Integer.valueOf(1), invokedParams.get()[0]);
Assert.assertEquals(Boolean.TRUE, invokedParams.get()[1]);
}
boolean internalPut(final T item, MultiItem<T> multiItem, String path, int maxWait, TimeUnit unit) throws Exception
{
if ( !blockIfMaxed(maxWait, unit) )
{
return false;
}
final MultiItem<T> givenMultiItem = multiItem;
if ( item != null )
{
final AtomicReference<T> ref = new AtomicReference<T>(item);
multiItem = new MultiItem<T>()
{
@Override
public T nextItem() throws Exception
{
return ref.getAndSet(null);
}
};
}
putCount.incrementAndGet();
byte[] bytes = ItemSerializer.serialize(multiItem, serializer);
if ( putInBackground )
{
doPutInBackground(item, path, givenMultiItem, bytes);
}
else
{
doPutInForeground(item, path, givenMultiItem, bytes);
}
return true;
}
@Override
public void onCompleted() {
GatewayConnection cur = currentConnection.get();
String nname = conn.isPrimary() ? "primary" : "secondary";
String aname = (cur == null) ? "unknown" : (cur.isPrimary() ? "primary" : "secondary");
AtomicReference<GatewayConnection> ref = conn.isPrimary() ? primaryConnection : secondaryConnection;
GatewayConnection old = ref.getAndSet(conn);
if (old != null) {
log.warn("{} gateway connection marked active while old one still alive, disconnnecting old connection", nname);
old.disconnect();
}
if (!updateCurrentConnection()) {
log.warn("{} gateway connection active but {} still connected, closing down {} connection", nname, aname, nname);
conn.disconnect();
return;
}
log.info("sending connected event on {} interface", conn.isPrimary() ? "primary" : "secondary");
IrisHal.NetworkInfo ni = IrisHal.getNetworkInfo();
ip.set(conn.isPrimary() ? ni.primaryIp : ni.secondaryIp);
netmask.set(conn.isPrimary() ? ni.primaryNetmask : ni.secondaryNetmask);
type.set(conn.isPrimary() ? ni.primaryInterfaceType : ni.secondaryInterfaceType);
PingSender ping = conn.isPrimary() ? primaryPingSender : secondaryPingSender;
ping.markConnected();
backoff.onSuccess();
Address addr = Address.hubService(HubAttributesService.getHubId(), "hub");
MessageBody msg = MessageBody.buildMessage(MessageConstants.MSG_HUB_CONNECTED_EVENT, HubAttributesService.asAttributeMap(false,true,false));
conn.send(PlatformMessage.buildEvent(msg, addr).create(), false);
LifeCycleService.setState(LifeCycle.CONNECTED);
}
public Iterable<ClassNode> iterateInheritanceChain(ClassNode cn) {
final AtomicReference<ClassNode> pCn = new AtomicReference<>(cn);
return () -> new Iterator<ClassNode>() {
@Override
public boolean hasNext() {
return pCn.get() != rootNode;
}
@Override
public ClassNode next() {
return pCn.getAndSet(getSuper(pCn.get()));
}
};
}
boolean internalPut(final T item, MultiItem<T> multiItem, String path, int maxWait, TimeUnit unit) throws Exception
{
if ( !blockIfMaxed(maxWait, unit) )
{
return false;
}
final MultiItem<T> givenMultiItem = multiItem;
if ( item != null )
{
final AtomicReference<T> ref = new AtomicReference<T>(item);
multiItem = new MultiItem<T>()
{
@Override
public T nextItem() throws Exception
{
return ref.getAndSet(null);
}
};
}
putCount.incrementAndGet();
byte[] bytes = ItemSerializer.serialize(multiItem, serializer);
if ( putInBackground )
{
doPutInBackground(item, path, givenMultiItem, bytes);
}
else
{
doPutInForeground(item, path, givenMultiItem, bytes);
}
return true;
}
@SuppressWarnings("unchecked")
public static <T> T getResult(AtomicReference<Object> atomic) throws Throwable{
await().untilAtomic(atomic, notNullValue());
Object result = atomic.getAndSet(null);
if(result instanceof Throwable)
throw (Throwable)result;
return (T)result;
}
/**
* Sets the new task and attempts to cancelTask the old one.
*
* @param taskRef task reference
* @param newTask new task
*/
private void swapAndCancelTask(AtomicReference<TimerTask> taskRef,
TimerTask newTask) {
TimerTask oldTask = taskRef.getAndSet(newTask);
if (oldTask != null) {
oldTask.cancel();
}
}
@SneakyThrows(Exception.class)
private void stopComponent(AtomicReference<? extends AutoCloseable> componentReference) {
AutoCloseable p = componentReference.getAndSet(null);
if (p != null) {
p.close();
}
}
private void delete(AtomicReference<File> fileRef) {
File f = fileRef.getAndSet(null);
if (f != null && f.exists()) {
if (FileHelpers.deleteFileOrDirectory(f)) {
log("Deleted '%s'.", f.getAbsolutePath());
}
}
}
@Test
public void executeJavaScript_delegatesToExecJs() {
AtomicReference<String> invokedExpression = new AtomicReference<>();
AtomicReference<Serializable[]> invokedParams = new AtomicReference<>();
Page page = new Page(new MockUI()) {
@Override
public PendingJavaScriptResult executeJs(String expression,
Serializable... parameters) {
String oldExpression = invokedExpression.getAndSet(expression);
Assert.assertNull("There should be no old expression",
oldExpression);
Serializable[] oldParams = invokedParams.getAndSet(parameters);
Assert.assertNull("There should be no old params", oldParams);
return null;
}
};
ExecutionCanceler executionCanceler = page.executeJavaScript("foo", 1,
true);
Assert.assertNull(executionCanceler);
Assert.assertEquals("foo", invokedExpression.get());
Assert.assertEquals(Integer.valueOf(1), invokedParams.get()[0]);
Assert.assertEquals(Boolean.TRUE, invokedParams.get()[1]);
}
public static void cancel(AtomicReference<Subscription> reference) {
Subscription actual = reference.getAndSet(CANCELLED);
if (actual != null && actual != CANCELLED) {
actual.cancel();
}
}
public static Throwable markFailureAsTerminated(AtomicReference<Throwable> failures) {
return failures.getAndSet(TERMINATED);
}
/**
* Change the {@link IHAPolicyLifeCycle} associated with this instance of
* this servlet. The new policy will be installed iff it can be initialized
* successfully. The old policy will be destroyed iff the new policy is
* successfully installed.
*
* @param newValue
* The new value (required).
* @param ref
* The {@link AtomicReference} object that holds the current
* value of the policy.
*
* TODO Since we are allowing programatic change of the policy,
* it would be a good idea to make that change atomic with
* respect to any specific request and to make the destroy of the
* policy something that occurs once any in flight request has
* been handled (there is more than one place where the policy is
* checked in the code). The atomic change might be accomplished
* by attaching the policy to the request as an attribute. The
* destroy could be achieved by reference counts for the #of in
* flight requests flowing through a policy. The request
* attribute and reference count could be handled together
* through handshaking with the policy when attaching it as a
* request attribute in
* {@link #service(HttpServletRequest, HttpServletResponse)}.
*/
private <T extends IHAPolicyLifeCycle> void setHAPolicy(final T newValue,
final AtomicReference<T> ref) {
final ServletConfig servletConfig = getServletConfig();
final ServletContext servletContext = servletConfig.getServletContext();
final IIndexManager indexManager = BigdataServlet
.getIndexManager(servletContext);
if (! ((AbstractJournal) indexManager).isHAJournal()) {
// This is not an error, but the LBS is only for HA.
log.warn("Not HA");
return;
}
try {
// Attempt to provision the specified LBS policy.
newValue.init(servletConfig, indexManager);
} catch (Throwable t) {
/*
* The specified LBS policy could not be provisioned.
*/
if (InnerCause.isInnerCause(t, InterruptedException.class)) {
// Interrupted.
return;
}
log.error("Could not setup policy: " + newValue, t);
try {
newValue.destroy();
} catch (Throwable t2) {
if (InnerCause.isInnerCause(t, InterruptedException.class)) {
// Interrupted.
return;
}
log.warn("Problem destroying policy: " + newValue, t2);
}
// The new policy will not be installed.
return;
}
// Install the new policy.
final T oldValue = ref.getAndSet(newValue);
if (oldValue != null && oldValue != newValue) {
// TODO Should await a zero reference count on the policy.
oldValue.destroy();
}
}
@Override
public Publisher<T> apply(Uni<T> uni) {
nonNull(uni, "uni");
// Several important points to note here
// 1. The subscription on this Uni must be done when we receive a request, not on the subscription
// 2. The request parameter must be checked to be compliant with Reactive Streams
// 3. Cancellation can happen 1) before the request (and so the uni subscription); 2) after the request but
// before the emission; 3) after the emission. In (1) the uni subscription must not happen. In (2), the emission
// must not happen. In (3), the emission could happen.
// 4. If the uni item is `null` the stream is completed. If the uni item is not `null`, the stream contains
// the item and the end of stream signal. In the case of error, the stream propagates the error.
return subscriber -> {
AtomicReference<UniSubscription> upstreamSubscription = new AtomicReference<>();
UniSubscription downstreamSubscription = new UniSubscription() {
@Override
public synchronized void request(long n) {
if (n <= 0) {
subscriber.onError(new IllegalArgumentException("Invalid request"));
return;
}
if (upstreamSubscription.get() == CANCELLED) {
return;
}
// We received a request, we subscribe to the uni
uni.subscribe().withSubscriber(new UniSubscriber<T>() {
@Override
public void onSubscribe(UniSubscription subscription) {
if (!upstreamSubscription.compareAndSet(null, subscription)) {
subscriber.onError(new IllegalStateException(
"Invalid subscription state - already have a subscription for upstream"));
}
}
@Override
public void onItem(T item) {
if (upstreamSubscription.getAndSet(CANCELLED) != CANCELLED) {
if (item != null) {
subscriber.onNext(item);
}
subscriber.onComplete();
}
}
@Override
public void onFailure(Throwable failure) {
if (upstreamSubscription.getAndSet(CANCELLED) != CANCELLED) {
subscriber.onError(failure);
}
}
});
}
@Override
public void cancel() {
UniSubscription upstream;
synchronized (this) {
upstream = upstreamSubscription.getAndSet(CANCELLED);
}
if (upstream != null) {
upstream.cancel();
}
}
};
subscriber.onSubscribe(downstreamSubscription);
};
}
public static void main(String[] args) {
Person person = new Person("zhangsan", 11);
AtomicReference<Person> atomicReference = new AtomicReference<>(person);
atomicReference.getAndSet(new Person("zhangsan", 12));
}
@Test(timeout=5000)
public void pause() throws Exception {
logTestStart();
testedBy(RequestValidator.class, "validateSubsequentPause");
final AtomicReference<AbstractBody> request =
new AtomicReference<AbstractBody>();
session.addBOSHClientRequestListener(new BOSHClientRequestListener() {
public void requestSent(final BOSHMessageEvent event) {
request.set(event.getBody());
}
});
// Initiate a session with a maxpause
session.send(ComposableBody.builder().build());
StubConnection conn = cm.awaitConnection();
AbstractBody scr = ComposableBody.builder()
.setAttribute(Attributes.SID, "123XYZ")
.setAttribute(Attributes.WAIT, "1")
.setAttribute(Attributes.MAXPAUSE, "2")
.build();
conn.sendResponse(scr);
session.drain();
// Send the pause request
request.set(null);
boolean result = session.pause();
assertTrue(result);
conn = cm.awaitConnection();
conn.sendResponse(ComposableBody.builder().build());
session.drain();
AbstractBody req = request.getAndSet(null);
assertEquals(scr.getAttribute(Attributes.MAXPAUSE),
req.getAttribute(Attributes.PAUSE));
try {
Thread.sleep(1000);
assertNull(request.get());
Thread.sleep(1000);
} catch (InterruptedException intx) {
fail("Interrupted while waiting");
}
req = request.get();
assertNotNull(req);
}