List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorCluster.java
@Test public void testLostRestart() throws Exception { final Timing timing = new Timing(); CuratorFramework client = null;/* ww w . j av a 2 s . c o m*/ TestingCluster cluster = new TestingCluster(3); cluster.start(); try { client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.sync("/", null); final AtomicReference<Exception> error = new AtomicReference<Exception>(null); final AtomicReference<String> lockNode = new AtomicReference<String>(null); final Semaphore semaphore = new Semaphore(0); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch internalLostLatch = new CountDownLatch(1); LeaderSelectorListener listener = new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { try { List<String> names = client.getChildren().forPath("/leader"); if (names.size() != 1) { semaphore.release(); Exception exception = new Exception("Names size isn't 1: " + names.size()); error.set(exception); return; } lockNode.set(names.get(0)); semaphore.release(); if (!timing.multiple(4).awaitLatch(internalLostLatch)) { error.set(new Exception("internalLostLatch await failed")); } } finally { lostLatch.countDown(); } } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { internalLostLatch.countDown(); } } }; LeaderSelector selector = new LeaderSelector(client, "/leader", listener); selector.start(); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); if (error.get() != null) { throw new AssertionError(error.get()); } Collection<InstanceSpec> instances = cluster.getInstances(); cluster.stop(); Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch)); timing.sleepABit(); Assert.assertFalse(selector.hasLeadership()); Assert.assertNotNull(lockNode.get()); cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()])); cluster.start(); try { client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration } catch (Exception ignore) { // ignore } Assert.assertTrue(semaphore.availablePermits() == 0); Assert.assertFalse(selector.hasLeadership()); selector.requeue(); Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); } finally { IOUtils.closeQuietly(client); IOUtils.closeQuietly(cluster); } }
From source file:com.oasisfeng.nevo.decorators.media.MediaPlayerDecorator.java
@Override protected void apply(final StatusBarNotificationEvo evolving) throws Exception { if (evolving.isClearable()) return; // Just sticky notification, to reduce the overhead. final INotification n = evolving.notification(); RemoteViews content_view = n.getBigContentView(); // Prefer big content view since it usually contains more actions if (content_view == null) content_view = n.getContentView(); if (content_view == null) return;/* w w w .j a v a 2s. c om*/ final AtomicReference<IntentSender> sender_holder = new AtomicReference<>(); final View views = content_view.apply(new ContextWrapper(this) { @Override public void startIntentSender(final IntentSender intent, final Intent fillInIntent, final int flagsMask, final int flagsValues, final int extraFlags) throws IntentSender.SendIntentException { startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null); } @Override public void startIntentSender(final IntentSender intent, final Intent fillInIntent, final int flagsMask, final int flagsValues, final int extraFlags, final Bundle options) throws IntentSender.SendIntentException { sender_holder.set(intent); } }, null); if (!(views instanceof ViewGroup)) return; final List<NotificationCompat.Action> actions = new ArrayList<>(8); findClickable((ViewGroup) views, new Predicate<View>() { @Override public boolean apply(final View v) { sender_holder.set(null); v.performClick(); // trigger startIntentSender() above final IntentSender sender = sender_holder.get(); if (sender == null) { Log.w(TAG, v + " has OnClickListener but no PendingIntent in it."); return true; } final PendingIntent pending_intent = getPendingIntent(sender); if (v instanceof TextView) { final CharSequence text = ((TextView) v).getText(); actions.add(new NotificationCompat.Action(0, text, pending_intent)); } else if (v instanceof ImageView) { final int res = getImageViewResource((ImageView) v); CharSequence title = v.getContentDescription(); if (title == null) title = "<" + System.identityHashCode(v); actions.add(new NotificationCompat.Action(res, title, pending_intent)); } else { CharSequence title = v.getContentDescription(); if (title == null) title = "<" + System.identityHashCode(v); actions.add(new NotificationCompat.Action(0, title, pending_intent)); } return true; } }); final Notification mirror; final String pkg = evolving.getPackageName(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final Notification.Builder b = new Notification.Builder(createPackageContext(pkg, 0)) .setContentTitle(n.extras().getCharSequence(NotificationCompat.EXTRA_TITLE)) .setLargeIcon(n.getLargeIcon()).setSmallIcon(fixIconPkg(n.getSmallIcon(), pkg)); for (final NotificationCompat.Action action : actions) b.addAction(new Action.Builder(Icon.createWithResource(pkg, action.getIcon()), action.getTitle(), action.getActionIntent()).build()); mirror = b.build(); } else { final NotificationCompat.Builder b = new NotificationCompat.Builder(createPackageContext(pkg, 0)) .setContentTitle(n.extras().getCharSequence(NotificationCompat.EXTRA_TITLE)) .setLargeIcon(n.extras().getParcelable(NotificationCompat.EXTRA_LARGE_ICON).<Bitmap>get()) .setSmallIcon(android.R.drawable.ic_media_play); for (final NotificationCompat.Action action : actions) b.addAction(action); mirror = b.build(); } final NotificationManagerCompat nm = NotificationManagerCompat.from(this); nm.notify("M<" + evolving.getPackageName() + (evolving.getTag() != null ? ">" + evolving.getTag() : ">"), evolving.getId(), mirror); }
From source file:de.sainth.recipe.backend.db.repositories.FoodRepository.java
public Food save(Food food) { AtomicReference<Food> bu = new AtomicReference<>(); create.transaction(configuration -> { Long id = using(configuration).select(FOODS.ID).from(FOODS).where(FOODS.NAME.eq(food.getName())) .forUpdate().fetchOneInto(Long.class); FoodsRecord record;//from ww w. j av a 2 s. co m if (id == null) { record = using(configuration) .insertInto(FOODS, FOODS.NAME, FOODS.POINTS, FOODS.POINTS_BASE_AMOUNT, FOODS.BASIC_UNIT) .values(food.getName(), food.getPoints(), food.getPointsBaseAmount(), food.getBasicUnit()) .returning().fetchOne(); } else { record = using(configuration).update(FOODS).set(FOODS.NAME, food.getName()) .set(FOODS.POINTS, food.getPoints()) .set(FOODS.POINTS_BASE_AMOUNT, food.getPointsBaseAmount()) .set(FOODS.BASIC_UNIT, food.getBasicUnit()).where(FOODS.ID.eq(id)).returning().fetchOne(); } bu.set(new Food(record.getId(), record.getName(), record.getPoints(), record.getPointsBaseAmount(), record.getBasicUnit())); }); return bu.get(); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.BaselineFolderCollection.java
public void processBaselineRequests(final Workspace workspace, final Iterable<BaselineRequest> requests, final boolean throwIfCanceled, final AtomicReference<Iterable<BaselineRequest>> outFailedLocalRequests) throws CoreCancelException { outFailedLocalRequests.set(null); // 1. The first async operation gzips content from the local disk and // places the resulting baseline files into the baseline folder. final BaselineUpdaterAsyncOperation localDiskAsyncOp = new BaselineUpdaterAsyncOperation(this); final TaskMonitor taskMonitor = TaskMonitorService.getTaskMonitor(); final AccountingCompletionService<WorkerStatus> completionService = new AccountingCompletionService<WorkerStatus>( workspace.getClient().getUploadDownloadWorkerExecutor()); try {/* w w w . j a v a 2 s.c o m*/ for (final BaselineRequest request : requests) { if (null != request.getSourceLocalItem()) { if (throwIfCanceled && taskMonitor.isCanceled()) { throw new CoreCancelException(); } completionService.submit(new BaselineUpdaterWorker(taskMonitor, request, localDiskAsyncOp)); } } } catch (final CoreCancelException e) { BaselineUpdaterAsyncOperation.waitForCompletions(completionService); throw e; } BaselineUpdaterAsyncOperation.waitForCompletions(completionService); testForFatalError(localDiskAsyncOp); // 2. The second async operation fetches content from the server and // places it into the baseline folder. It also handles delete requests // (no DownloadUrl or SourceLocalItem). final BaselineDownloadAsyncOperation downloadAsyncOp = new BaselineDownloadAsyncOperation(); final VersionControlClient client = workspace.getClient(); try { for (final BaselineRequest request : requests) { if (null == request.getSourceLocalItem()) { if (null != request.getDownloadURL()) { final BaselineDownloadWorker worker = new BaselineDownloadWorker(EventSource.newFromHere(), taskMonitor, client, downloadAsyncOp, request.getDownloadURL(), this, request.getBaselineFileGUID()); if (throwIfCanceled && taskMonitor.isCanceled()) { throw new CoreCancelException(); } completionService.submit(worker); } else { // This is a delete request. deleteBaseline(request.getBaselineFileGUID()); } } } // 2B. Re-process the requests which failed in step #1, but have a // DownloadUrl for fallback. One reason a request might be in this // list is failing a hash check. for (final BaselineRequest request : localDiskAsyncOp.getFailedRequests()) { if (null != request.getDownloadURL()) { final BaselineDownloadWorker worker = new BaselineDownloadWorker(EventSource.newFromHere(), taskMonitor, client, downloadAsyncOp, request.getDownloadURL(), this, request.getBaselineFileGUID()); if (throwIfCanceled && taskMonitor.isCanceled()) { throw new CoreCancelException(); } completionService.submit(worker); } } } catch (final CoreCancelException e) { BaselineDownloadAsyncOperation.waitForCompletions(completionService); throw e; } BaselineDownloadAsyncOperation.waitForCompletions(completionService); testForFatalError(downloadAsyncOp); outFailedLocalRequests.set(localDiskAsyncOp.getFailedRequests()); }
From source file:eu.eubrazilcc.lvl.storage.oauth2.dao.ResourceOwnerDAO.java
/** * Checks whether or not the specified user exists (the specified username coincides with the * username stored for the resource owner identified by the provided id). * @param ownerId - identifier of the resource owner * @param username - user name to be validated, or email address if {@code useEmail} is set to true * @param scopeRef - if set and the resource owner is valid, then the scopes associated with the resource * owner are concatenated and returned to the caller to be used with OAuth * @return {@code true} only if the provided identifier and user name coincide with those stored for the * resource owner. Otherwise, returns {@code false}. */// w w w . j a va 2s . c o m public boolean exist(final String ownerId, final String username, final @Nullable AtomicReference<String> scopeRef) { checkArgument(isNotBlank(ownerId), "Uninitialized or invalid resource owner id"); checkArgument(isNotBlank(username), "Uninitialized or invalid username"); final ResourceOwner resourceOwner = find(ownerId); final boolean exist = (resourceOwner != null && resourceOwner.getUser() != null && username.equals(resourceOwner.getUser().getUserid())); if (exist && scopeRef != null) { scopeRef.set(oauthScope(resourceOwner, false)); } return exist; }
From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java
private void processUpdates(Collection<UpdateEntry> updates) { if (closed) { return;//from w w w . j ava 2s. com } updates.forEach(update -> { final String key = update.key(); final MapValue value = update.value() == null ? null : update.value().copy(); if (value == null || value.isTombstone()) { MapValue previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value)); if (previousValue != null && previousValue.isAlive()) { notifyListeners( new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue))); } } else { counter.incrementCount(); AtomicReference<byte[]> oldValue = new AtomicReference<>(); AtomicBoolean updated = new AtomicBoolean(false); items.compute(key, (k, existing) -> { if (existing == null || value.isNewerThan(existing)) { updated.set(true); oldValue.set(existing != null ? existing.get() : null); return value; } return existing; }); if (updated.get()) { if (oldValue.get() == null) { notifyListeners(new MapDelegateEvent<>(INSERT, decodeKey(key), decodeValue(value.get()))); } else { notifyListeners(new MapDelegateEvent<>(UPDATE, decodeKey(key), decodeValue(value.get()))); } } } }); }
From source file:org.apache.hadoop.hdfs.server.namenode.TestEditLogRace.java
/** * Most of the FSNamesystem methods have a synchronized section where they * update the name system itself and write to the edit log, and then * unsynchronized, they call logSync. This test verifies that, if an * operation has written to the edit log but not yet synced it, * we wait for that sync before entering safe mode. *///from w w w .j av a2 s . com public void testSaveRightBeforeSync() throws Exception { Configuration conf = getConf(); NameNode.format(conf); NameNode fakeNN = mock(NameNode.class); NameNode.myMetrics = new NameNodeMetrics(conf, fakeNN); Mockito.doReturn(new InetSocketAddress("127.0.0.1", 12345)).when(fakeNN).getNameNodeAddress(); final FSNamesystem namesystem = new FSNamesystem(fakeNN, conf); try { FSImage fsimage = namesystem.getFSImage(); FSEditLog editLog = spy(fsimage.getEditLog()); fsimage.editLog = editLog; final AtomicReference<Throwable> deferredException = new AtomicReference<Throwable>(); final CountDownLatch waitToEnterSync = new CountDownLatch(1); final Thread doAnEditThread = new Thread() { public void run() { try { LOG.info("Starting mkdirs"); namesystem.mkdirs("/test", new PermissionStatus("test", "test", new FsPermission((short) 00755))); LOG.info("mkdirs complete"); } catch (Throwable ioe) { deferredException.set(ioe); waitToEnterSync.countDown(); } } }; Answer<Void> blockingSync = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { LOG.info("logSync called"); if (Thread.currentThread() == doAnEditThread) { LOG.info("edit thread: Telling main thread we made it just before logSync..."); waitToEnterSync.countDown(); LOG.info("edit thread: sleeping for " + BLOCK_TIME + "secs"); Thread.sleep(BLOCK_TIME * 1000); LOG.info("Going through to logSync. This will allow the main thread to continue."); } invocation.callRealMethod(); LOG.info("logSync complete"); return null; } }; doAnswer(blockingSync).when(editLog).logSync(); doAnEditThread.start(); LOG.info("Main thread: waiting to just before logSync..."); waitToEnterSync.await(); assertNull(deferredException.get()); LOG.info("Main thread: detected that logSync about to be called."); LOG.info("Trying to enter safe mode."); LOG.info("This should block for " + BLOCK_TIME + "sec, since we have pending edits"); long st = System.currentTimeMillis(); namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER); long et = System.currentTimeMillis(); LOG.info("Entered safe mode"); // Make sure we really waited for the flush to complete! assertTrue(et - st > (BLOCK_TIME - 1) * 1000); // Once we're in safe mode, save namespace. namesystem.saveNamespace(); LOG.info("Joining on edit thread..."); doAnEditThread.join(); assertNull(deferredException.get()); verifyEditLogs(fsimage); } finally { LOG.info("Closing namesystem"); if (namesystem != null) namesystem.close(); } }
From source file:org.apache.hadoop.hdfs.server.namenode.TestEditLogRace.java
/** * The logSync() method in FSEditLog is unsynchronized whiel syncing * so that other threads can concurrently enqueue edits while the prior * sync is ongoing. This test checks that the log is saved correctly * if the saveImage occurs while the syncing thread is in the unsynchronized middle section. * //from w w w . j a v a2 s .co m * This replicates the following manual test proposed by Konstantin: * I start the name-node in debugger. * I do -mkdir and stop the debugger in logSync() just before it does flush. * Then I enter safe mode with another client * I start saveNamepsace and stop the debugger in * FSImage.saveFSImage() -> FSEditLog.createEditLogFile() * -> EditLogFileOutputStream.create() -> * after truncating the file but before writing LAYOUT_VERSION into it. * Then I let logSync() run. * Then I terminate the name-node. * After that the name-node wont start, since the edits file is broken. */ public void testSaveImageWhileSyncInProgress() throws Throwable { Configuration conf = getConf(); NameNode.format(conf); NameNode fakeNN = mock(NameNode.class); NameNode.myMetrics = new NameNodeMetrics(conf, fakeNN); Mockito.doReturn(new InetSocketAddress("127.0.0.1", 12345)).when(fakeNN).getNameNodeAddress(); final FSNamesystem namesystem = new FSNamesystem(fakeNN, conf); try { FSImage fsimage = namesystem.getFSImage(); FSEditLog editLog = fsimage.getEditLog(); ArrayList<EditLogOutputStream> streams = editLog.getEditStreams(); EditLogOutputStream spyElos = spy(streams.get(0)); streams.set(0, spyElos); final AtomicReference<Throwable> deferredException = new AtomicReference<Throwable>(); final CountDownLatch waitToEnterFlush = new CountDownLatch(1); final Thread doAnEditThread = new Thread() { public void run() { try { LOG.info("Starting mkdirs"); namesystem.mkdirs("/test", new PermissionStatus("test", "test", new FsPermission((short) 00755))); LOG.info("mkdirs complete"); } catch (Throwable ioe) { deferredException.set(ioe); waitToEnterFlush.countDown(); } } }; Answer<Void> blockingFlush = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { LOG.info("Flush called"); if (Thread.currentThread() == doAnEditThread) { LOG.info("edit thread: Telling main thread we made it to flush section..."); // Signal to main thread that the edit thread is in the racy section waitToEnterFlush.countDown(); LOG.info("edit thread: sleeping for " + BLOCK_TIME + "secs"); Thread.sleep(BLOCK_TIME * 1000); LOG.info("Going through to flush. This will allow the main thread to continue."); } invocation.callRealMethod(); LOG.info("Flush complete"); return null; } }; doAnswer(blockingFlush).when(spyElos).flush(); doAnEditThread.start(); // Wait for the edit thread to get to the logsync unsynchronized section LOG.info("Main thread: waiting to enter flush..."); waitToEnterFlush.await(); if (deferredException.get() != null) { throw deferredException.get(); } LOG.info("Main thread: detected that logSync is in unsynchronized section."); LOG.info("Trying to enter safe mode."); LOG.info("This should block for " + BLOCK_TIME + "sec, since flush will sleep that long"); long st = System.currentTimeMillis(); namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER); long et = System.currentTimeMillis(); LOG.info("Entered safe mode"); // Make sure we really waited for the flush to complete! assertTrue(et - st > (BLOCK_TIME - 1) * 1000); // Once we're in safe mode, save namespace. namesystem.saveNamespace(); LOG.info("Joining on edit thread..."); doAnEditThread.join(); assertNull(deferredException.get()); verifyEditLogs(fsimage); } finally { LOG.info("Closing namesystem"); if (namesystem != null) namesystem.close(); } }
From source file:org.helios.jzab.agent.net.active.ActiveClient.java
/** * Modifies the passed channel's pipeline to handle a request response * @param channel The channel to modify the pipeline for * @param result A reference container for the result * @param exception A reference container for any thrown exception * @return the modified channel//from w ww .java 2 s . com */ protected <T> Channel modfyRequestResponseChannel(Channel channel, final Class<T> responseType, final AtomicReference<T> result, final AtomicReference<Throwable> exception) { channel.getPipeline().remove("routingHandler1"); channel.getPipeline().remove("routingHandler2"); channel.getPipeline().addAfter("responseDecoder", "requestResponseHandler", new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final Object response = e.getMessage(); try { result.set(responseType.cast(response)); } catch (Exception ex) { exception.set(new Exception("Incompatible Result Type [" + response == null ? "<null>" : response.getClass().getName() + "] but was expecting [" + responseType.getClass().getName() + "]", ex)); } super.messageReceived(ctx, e); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { exception.set(e.getCause()); } }); return channel; }
From source file:com.coinblesk.client.MainActivity.java
private void initSwitch(Menu menu) { MenuItem item = menu.findItem(R.id.myswitch); View view = item.getActionView(); final Switch mySwitch = (Switch) view.findViewById(R.id.switchAB); final AtomicReference<CountDownTimer> ref = new AtomicReference<>(); mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override/*w w w .j a va2s . co m*/ public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { //enable BT ref.set(new CountDownTimer(30000, 1000) { int i = 0; public void onTick(final long millisUntilFinished) { mySwitch.setButtonDrawable( (i++ % 2) == 0 ? R.drawable.bluetooth_onon : R.drawable.bluetooth_on); mySwitch.setTextOn("" + millisUntilFinished / 1000); } public void onFinish() { mySwitch.setButtonDrawable(R.drawable.bluetooth_on); mySwitch.setChecked(false); } }); ref.get().start(); LocalBroadcastManager.getInstance(MainActivity.this) .sendBroadcast(new Intent(Constants.START_CLIENTS_ACTION)); } else { //mySwitch.setShowText(false); CountDownTimer tmp; if ((tmp = ref.getAndSet(null)) != null) { tmp.cancel(); } LocalBroadcastManager.getInstance(MainActivity.this) .sendBroadcast(new Intent(Constants.STOP_CLIENTS_ACTION)); } } }); }