List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java
/** * Test that when 2 update loops both manage to write, but conflict on * updating the local value./*from w w w . jav a 2s. c o m*/ */ @Test public void testConflictOnLocalUpdate() throws Exception { try (DeferCallbacksMockLedgerManager lm = spy(new DeferCallbacksMockLedgerManager(1))) { long ledgerId = 1234L; BookieSocketAddress b0 = new BookieSocketAddress("0.0.0.0:3181"); BookieSocketAddress b1 = new BookieSocketAddress("0.0.0.1:3181"); BookieSocketAddress b2 = new BookieSocketAddress("0.0.0.2:3181"); BookieSocketAddress b3 = new BookieSocketAddress("0.0.0.3:3181"); LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(2) .withDigestType(DigestType.CRC32C).withPassword(new byte[0]).withWriteQuorumSize(2) .newEnsembleEntry(0L, Lists.newArrayList(b0, b1)).build(); Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get(); AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata); CompletableFuture<Versioned<LedgerMetadata>> loop1 = new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b0), (currentMetadata) -> { List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L)); ensemble.set(0, b2); return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble) .build(); }, reference::compareAndSet).run(); lm.waitForWriteCount(1); CompletableFuture<Versioned<LedgerMetadata>> loop2 = new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b1), (currentMetadata) -> { List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L)); ensemble.set(1, b3); return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble) .build(); }, reference::compareAndSet).run(); Assert.assertEquals(loop2.get(), reference.get()); lm.runDeferred(); Assert.assertEquals(loop1.get(), reference.get()); Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2); Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b3); verify(lm, times(3)).writeLedgerMetadata(anyLong(), any(), any()); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java
private Workstation(final WorkstationType type, final PersistenceStoreProvider persistenceProvider) { Check.notNull(type, "type"); //$NON-NLS-1$ this.type = type; if (type == WorkstationType.CURRENT) { Check.notNull(persistenceProvider, "persistenceProvider"); //$NON-NLS-1$ synchronized (cacheMutex) { // Detect if cache directory is available cacheDirectory = getCacheDirectory(persistenceProvider); cacheEnabled = cacheDirectory != null ? ensureLocalPathIsUsable(cacheDirectory, InternalCacheLoader.FILE_NAME) : false;//from www . j av a 2 s .c om workspaceCacheFile = cacheEnabled ? new File(cacheDirectory, InternalCacheLoader.FILE_NAME) : null; /* * Load the cache. After this, it will be reloaded by the Cache * property when the FSW sets the flag indicating the cache file * changed. Use the Cache property everywhere else. We are not * performing any merging on mappings, so we can safely ignore * the warnings */ final AtomicReference<InternalWorkspaceConflictInfo[]> conflictingWorkspaces = new AtomicReference<InternalWorkspaceConflictInfo[]>(); workspaceCache = InternalCacheLoader.loadConfig(null, cacheEnabled, conflictingWorkspaces, cacheMutex, workspaceCacheFile); Check.isTrue(conflictingWorkspaces.get().length == 0, "conflictingWorkspaces.get().length == 0"); //$NON-NLS-1$ } synchronized (configurationMutex) { // Detect if configuration directory is available configurationDirectory = getConfigurationDirectory(persistenceProvider); configurationEnabled = configurationDirectory != null ? ensureLocalPathIsUsable(configurationDirectory, LocalItemExclusionCache.FILE_NAME) : false; localItemExclusionCacheFile = configurationEnabled ? new File(configurationDirectory, LocalItemExclusionCache.FILE_NAME) : null; } } else { cacheDirectory = null; cacheEnabled = false; workspaceCacheFile = null; configurationDirectory = null; configurationEnabled = false; localItemExclusionCacheFile = null; } }
From source file:com.jeremydyer.processors.salesforce.GenerateSOQL.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final FlowFile flowFile = session.get(); if (flowFile == null) { return;//from ww w . ja va 2s . c o m } final AtomicReference<String> query_url = new AtomicReference<>(); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream inputStream) throws IOException { String jsonString = IOUtils.toString(inputStream); JSONObject json = new JSONObject(jsonString); JSONArray fields = json.getJSONArray("fields"); StringBuffer buffer = new StringBuffer(); buffer.append(context.getProperty(SALESFORCE_SERVER_INSTANCE).evaluateAttributeExpressions(flowFile) .getValue()); buffer.append("/services/data/v36.0/queryAll/?q="); buffer.append("SELECT "); //Loops through the fields and builds the SOQL for (int i = 0; i < fields.length() - 1; i++) { buffer.append(fields.getJSONObject(i).getString("name")); buffer.append(","); } //Append the last field name buffer.append(fields.getJSONObject(fields.length() - 1).getString("name")); buffer.append(" FROM " + TABLE_NAME); buffer.append(" WHERE SYSTEMMODSTAMP > "); buffer.append( context.getProperty(LAST_SYNC_TIME).evaluateAttributeExpressions(flowFile).getValue()); buffer.append(" order by SYSTEMMODSTAMP asc"); String soql = buffer.toString(); //Replace all spaces with + as required by Salesforce soql = soql.replace(" ", "+"); query_url.set(soql); } }); FlowFile ff = session.putAttribute(flowFile, "SOQL_QUERY_URL", query_url.get()); session.transfer(ff, REL_SUCCESS); }
From source file:info.archinnov.achilles.test.integration.tests.AsyncBatchModeIT.java
@Test public void should_batch_counters_async() throws Exception { // Start batch AsyncBatch batch = asyncManager.createBatch(); batch.startBatch();//from w ww.j a v a 2s. c om CompleteBean entity = CompleteBeanTestBuilder.builder().randomId().name("name").buid(); entity = batch.insert(entity); entity.setLabel("label"); Tweet welcomeTweet = TweetTestBuilder.tweet().randomId().content("welcomeTweet").buid(); entity.setWelcomeTweet(welcomeTweet); entity.getVersion().incr(10L); batch.update(entity); RegularStatement selectLabel = select("label").from("CompleteBean").where(eq("id", entity.getId())); Map<String, Object> result = asyncManager.nativeQuery(selectLabel).getFirst().getImmediately(); assertThat(result).isNull(); RegularStatement selectCounter = select("counter_value").from("achilles_counter_table") .where(eq("fqcn", CompleteBean.class.getCanonicalName())) .and(eq("primary_key", entity.getId().toString())).and(eq("property_name", "version")); result = asyncManager.nativeQuery(selectCounter).getFirst().getImmediately(); assertThat(result).isNull(); final CountDownLatch latch = new CountDownLatch(2); final AtomicReference<Object> successSpy = new AtomicReference<>(); final AtomicReference<Throwable> exceptionSpy = new AtomicReference<>(); FutureCallback<Object> successCallBack = new FutureCallback<Object>() { @Override public void onSuccess(Object result) { successSpy.getAndSet(result); latch.countDown(); } @Override public void onFailure(Throwable t) { latch.countDown(); } }; FutureCallback<Object> errorCallBack = new FutureCallback<Object>() { @Override public void onSuccess(Object result) { latch.countDown(); } @Override public void onFailure(Throwable t) { exceptionSpy.getAndSet(t); latch.countDown(); } }; // Flush batch.asyncEndBatch(successCallBack, errorCallBack); latch.await(); Statement statement = new SimpleStatement("SELECT label from CompleteBean where id=" + entity.getId()); Row row = asyncManager.getNativeSession().execute(statement).one(); assertThat(row.getString("label")).isEqualTo("label"); result = asyncManager.nativeQuery(selectCounter).getFirst().getImmediately(); assertThat(result.get("counter_value")).isEqualTo(10L); assertThatBatchContextHasBeenReset(batch); assertThat(successSpy.get()).isNotNull().isSameAs(Empty.INSTANCE); assertThat(exceptionSpy.get()).isNull(); }
From source file:TestFuseDFS.java
/** * Test concurrent creation and access of the mount */// ww w . j av a2 s . c o m @Test public void testMultipleThreads() throws IOException { ArrayList<Thread> threads = new ArrayList<Thread>(); final AtomicReference<String> errorMessage = new AtomicReference<String>(); for (int i = 0; i < 10; i++) { Thread t = new Thread() { public void run() { try { File d = new File(mountPoint, "dir" + getId()); execWaitRet("mkdir " + d.getAbsolutePath()); for (int j = 0; j < 10; j++) { File f = new File(d, "file" + j); final String contents = "thread " + getId() + " " + j; createFile(f, contents); } for (int j = 0; j < 10; j++) { File f = new File(d, "file" + j); execWaitRet("cat " + f.getAbsolutePath()); execWaitRet("rm " + f.getAbsolutePath()); } execWaitRet("rmdir " + d.getAbsolutePath()); } catch (IOException ie) { errorMessage.set(String.format("Exception %s", StringUtils.stringifyException(ie))); } } }; t.start(); threads.add(t); } for (Thread t : threads) { try { t.join(); } catch (InterruptedException ie) { fail("Thread interrupted: " + ie.getMessage()); } } assertNull(errorMessage.get(), errorMessage.get()); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.WorkspaceVersionTable.java
private void add(final WorkspaceLocalItem lvEntry, final boolean fromLoad) { final AtomicReference<WorkspaceLocalItem> atomicMatch = new AtomicReference<WorkspaceLocalItem>(); // Create a callback. final ModifyInPlaceCallback<WorkspaceLocalItemPair> callback = new ModifyInPlaceCallback<WorkspaceLocalItemPair>() { @Override/*from w w w . j a v a 2 s . c o m*/ public WorkspaceLocalItemPair invoke(final String token, WorkspaceLocalItemPair pair, final Object param) { if (pair == null) { pair = new WorkspaceLocalItemPair(); } if (lvEntry.isCommitted()) { atomicMatch.set(pair.getCommitted()); pair.setCommitted(lvEntry); } else { atomicMatch.set(pair.getUncommitted()); pair.setUncommitted(lvEntry); } return pair; } }; // Insert by the primary key (ServerItem, IsCommitted). server.modifyInPlace(lvEntry.getServerItem(), callback, null); final WorkspaceLocalItem matchingEntry = atomicMatch.get(); setDirty(!fromLoad); // Remove the replaced entry from other indexes. if (null != matchingEntry) { final String localItem = matchingEntry.getLocalItem(); if (localItem != null && localItem.length() > 0) { local.remove(localItem, false); } if (matchingEntry.isPendingReconcile()) { pendingReconcileCount--; } } if (lvEntry.isPendingReconcile()) { pendingReconcileCount++; } // Add the entry to the LocalItem tree if necessary. final String localItem = lvEntry.getLocalItem(); if (localItem != null && localItem.length() > 0) { local.add(localItem, lvEntry, true); } }
From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java
/** * Test that when 2 updates loops try to make the same modification, and they * conflict on the write to the store, the one that receives the conflict won't * try to write again, as the value is now correct. *//*w w w . j av a2s.c o m*/ @Test public void testConflictOnWriteBothWritingSame() throws Exception { try (BlockableMockLedgerManager lm = spy(new BlockableMockLedgerManager())) { lm.blockWrites(); long ledgerId = 1234L; BookieSocketAddress b0 = new BookieSocketAddress("0.0.0.0:3181"); BookieSocketAddress b1 = new BookieSocketAddress("0.0.0.1:3181"); BookieSocketAddress b2 = new BookieSocketAddress("0.0.0.2:3181"); LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(2) .withDigestType(DigestType.CRC32C).withPassword(new byte[0]).withWriteQuorumSize(2) .newEnsembleEntry(0L, Lists.newArrayList(b0, b1)).build(); Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get(); AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata); CompletableFuture<Versioned<LedgerMetadata>> loop1 = new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b0), (currentMetadata) -> { List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L)); ensemble.set(0, b2); return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble) .build(); }, reference::compareAndSet).run(); CompletableFuture<Versioned<LedgerMetadata>> loop2 = new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(b0), (currentMetadata) -> { List<BookieSocketAddress> ensemble = Lists.newArrayList(currentMetadata.getEnsembleAt(0L)); ensemble.set(0, b2); return LedgerMetadataBuilder.from(currentMetadata).replaceEnsembleEntry(0L, ensemble) .build(); }, reference::compareAndSet).run(); lm.releaseWrites(); Assert.assertEquals(loop1.get(), loop2.get()); Assert.assertEquals(loop1.get(), reference.get()); Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(0), b2); Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L).get(1), b1); verify(lm, times(2)).writeLedgerMetadata(anyLong(), any(), any()); } }
From source file:com.networknt.openapi.ValidatorHandlerTest.java
@Test public void testValidPost() throws Exception { final AtomicReference<ClientResponse> reference = new AtomicReference<>(); final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try {//from w ww . ja v a2 s . c o m connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e); } try { String post = "{\"id\":0,\"category\":{\"id\":0,\"name\":\"string\"},\"name\":\"doggie\",\"photoUrls\":[\"string\"],\"tags\":[{\"id\":0,\"name\":\"string\"}],\"status\":\"available\"}"; connection.getIoThread().execute(new Runnable() { @Override public void run() { final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/v1/pets"); request.getRequestHeaders().put(Headers.HOST, "localhost"); request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json"); request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked"); connection.sendRequest(request, client.createClientCallback(reference, latch, post)); } }); latch.await(10, TimeUnit.SECONDS); } catch (Exception e) { logger.error("IOException: ", e); throw new ClientException(e); } finally { IoUtils.safeClose(connection); } int statusCode = reference.get().getResponseCode(); String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY); Assert.assertEquals(200, statusCode); if (statusCode == 200) { Assert.assertNotNull(body); Assert.assertEquals("addPet", body); } }
From source file:com.android.ide.eclipse.adt.internal.editors.layout.gre.ClientRulesEngine.java
@Override public String displayFragmentSourceInput() { try {/* w ww .ja v a 2s . c om*/ // Compute a search scope: We need to merge all the subclasses // android.app.Fragment and android.support.v4.app.Fragment IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); IProject project = mRulesEngine.getProject(); final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); if (javaProject != null) { IType oldFragmentType = javaProject.findType(CLASS_V4_FRAGMENT); // First check to make sure fragments are available, and if not, // warn the user. IAndroidTarget target = Sdk.getCurrent().getTarget(project); // No, this should be using the min SDK instead! if (target.getVersion().getApiLevel() < 11 && oldFragmentType == null) { // Compatibility library must be present MessageDialog dialog = new MessageDialog(Display.getCurrent().getActiveShell(), "Fragment Warning", null, "Fragments require API level 11 or higher, or a compatibility " + "library for older versions.\n\n" + " Do you want to install the compatibility library?", MessageDialog.QUESTION, new String[] { "Install", "Cancel" }, 1 /* default button: Cancel */); int answer = dialog.open(); if (answer == 0) { if (!AddSupportJarAction.install(project)) { return null; } } else { return null; } } // Look up sub-types of each (new fragment class and compatibility fragment // class, if any) and merge the two arrays - then create a scope from these // elements. IType[] fragmentTypes = new IType[0]; IType[] oldFragmentTypes = new IType[0]; if (oldFragmentType != null) { ITypeHierarchy hierarchy = oldFragmentType.newTypeHierarchy(new NullProgressMonitor()); oldFragmentTypes = hierarchy.getAllSubtypes(oldFragmentType); } IType fragmentType = javaProject.findType(CLASS_FRAGMENT); if (fragmentType != null) { ITypeHierarchy hierarchy = fragmentType.newTypeHierarchy(new NullProgressMonitor()); fragmentTypes = hierarchy.getAllSubtypes(fragmentType); } IType[] subTypes = new IType[fragmentTypes.length + oldFragmentTypes.length]; System.arraycopy(fragmentTypes, 0, subTypes, 0, fragmentTypes.length); System.arraycopy(oldFragmentTypes, 0, subTypes, fragmentTypes.length, oldFragmentTypes.length); scope = SearchEngine.createJavaSearchScope(subTypes, IJavaSearchScope.SOURCES); } Shell parent = AdtPlugin.getShell(); final AtomicReference<String> returnValue = new AtomicReference<String>(); final AtomicReference<SelectionDialog> dialogHolder = new AtomicReference<SelectionDialog>(); final SelectionDialog dialog = JavaUI.createTypeDialog(parent, new ProgressMonitorDialog(parent), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, // Use ? as a default filter to fill dialog with matches "?", //$NON-NLS-1$ new TypeSelectionExtension() { @Override public Control createContentArea(Composite parentComposite) { Composite composite = new Composite(parentComposite, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Button button = new Button(composite, SWT.PUSH); button.setText("Create New..."); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String fqcn = createNewFragmentClass(javaProject); if (fqcn != null) { returnValue.set(fqcn); dialogHolder.get().close(); } } }); return composite; } @Override public ITypeInfoFilterExtension getFilterExtension() { return new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor typeInfoRequestor) { int modifiers = typeInfoRequestor.getModifiers(); if (!Flags.isPublic(modifiers) || Flags.isInterface(modifiers) || Flags.isEnum(modifiers)) { return false; } return true; } }; } }); dialogHolder.set(dialog); dialog.setTitle("Choose Fragment Class"); dialog.setMessage("Select a Fragment class (? = any character, * = any string):"); if (dialog.open() == IDialogConstants.CANCEL_ID) { return null; } if (returnValue.get() != null) { return returnValue.get(); } Object[] types = dialog.getResult(); if (types != null && types.length > 0) { return ((IType) types[0]).getFullyQualifiedName(); } } catch (JavaModelException e) { AdtPlugin.log(e, null); } catch (CoreException e) { AdtPlugin.log(e, null); } return null; }
From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java
@Test public void shouldFireKeepAlive() throws Exception { final AtomicInteger keepAliveEventCounter = new AtomicInteger(); final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference(); QueryHandler testHandler = new QueryHandler(endpoint, responseRingBuffer, queue, false) { @Override/*from w w w. j a v a 2 s . c om*/ public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); ctxRef.compareAndSet(null, ctx); } @Override protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) { assertEquals(1, keepAliveEventCounter.incrementAndGet()); } @Override protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) { assertEquals(2, keepAliveEventCounter.incrementAndGet()); } }; EmbeddedChannel channel = new EmbeddedChannel(testHandler); //test idle event triggers a query keepAlive request and hook is called testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT); assertEquals(1, keepAliveEventCounter.get()); assertTrue(queue.peek() instanceof QueryHandler.KeepAliveRequest); QueryHandler.KeepAliveRequest keepAliveRequest = (QueryHandler.KeepAliveRequest) queue.peek(); //test responding to the request with http response is interpreted into a KeepAliveResponse and hook is called HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); LastHttpContent responseEnd = new DefaultLastHttpContent(); channel.writeInbound(response, responseEnd); QueryHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable() .cast(QueryHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single(); ReferenceCountUtil.releaseLater(response); ReferenceCountUtil.releaseLater(responseEnd); assertEquals(2, keepAliveEventCounter.get()); assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status()); }