List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference
public AtomicReference()
From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java
@Test(timeout = 20000L) public void testConcurrency() throws Exception { httpServer.setAuthentication("testuser", "testpass"); auth = new AuthenticationBuilder().addUsername("testuser").addPassword("testpass").build(); newTransporter(httpServer.getHttpUrl()); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread threads[] = new Thread[20]; for (int i = 0; i < threads.length; i++) { final String path = "repo/file.txt?i=" + i; threads[i] = new Thread() { @Override//w ww .j a v a2 s .c o m public void run() { try { for (int j = 0; j < 100; j++) { GetTask task = new GetTask(URI.create(path)); transporter.get(task); assertEquals("test", task.getDataString()); } } catch (Throwable t) { error.compareAndSet(null, t); System.err.println(path); t.printStackTrace(); } } }; threads[i].setName("Task-" + i); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } assertNull(String.valueOf(error.get()), error.get()); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java
/** * Loads into the cache the workspaces residing in the specified source * control repository and having the specified owner. * * @param client//w w w. ja va 2 s. c om * the client (must not be <code>null</code>) * @param ownerName * the owner of the workspaces (must not be <code>null</code> or * empty) */ public void updateWorkspaceInfoCache(final VersionControlClient client, final String ownerName) { updateWorkspaceInfoCache(client, ownerName, new AtomicReference<Workspace[]>()); }
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 {//from w ww .ja v a2s . c om rootResource.set(servletContext.getResource("/")); } catch (MalformedURLException ex) { throw new ServletException(ex); } }); this.webServer.start(); assertThat(rootResource.get()).isNotNull(); }
From source file:io.cloudslang.lang.tools.build.SlangBuilderTest.java
@Test public void testProcessRunTestsMixed() { final Map<String, SlangTestCase> testCases = new LinkedHashMap<>(); final SlangTestCase testCase1 = new SlangTestCase("test1", "testFlowPath", "desc", asList("abc", "new"), "mock", null, null, false, "SUCCESS"); final SlangTestCase testCase2 = new SlangTestCase("test2", "testFlowPath", "desc", asList("efg", "new"), "mock", null, null, false, "SUCCESS"); final SlangTestCase testCase3 = new SlangTestCase("test3", "testFlowPath", "desc", asList("new", "new2"), "mock", null, null, false, "SUCCESS"); final SlangTestCase testCase4 = new SlangTestCase("test4", "testFlowPath", "desc", asList("new", "new2"), "mock", null, null, false, "SUCCESS"); testCases.put("test1", testCase1); testCases.put("test2", testCase2); testCases.put("test3", testCase3); testCases.put("test4", testCase4); final List<String> testSuites = newArrayList("new"); final Map<String, CompilationArtifact> compiledFlows = new HashMap<>(); final String projectPath = "aaa"; final AtomicReference<ThreadSafeRunTestResults> theCapturedArgument = new AtomicReference<>(); final AtomicReference<Map<String, SlangTestCase>> capturedTestsSeq = new AtomicReference<>(); final AtomicReference<Map<String, SlangTestCase>> capturedTestsPar = new AtomicReference<>(); doCallRealMethod().when(slangTestRunner).isTestCaseInActiveSuite(any(SlangTestCase.class), anyList()); doReturn(SlangBuildMain.TestCaseRunMode.SEQUENTIAL).doReturn(SlangBuildMain.TestCaseRunMode.PARALLEL) .doReturn(SlangBuildMain.TestCaseRunMode.PARALLEL) .doReturn(SlangBuildMain.TestCaseRunMode.SEQUENTIAL).when(testRunInfoService) .getRunModeForTestCase(any(SlangTestCase.class), any(ConflictResolutionStrategy.class), any(DefaultResolutionStrategy.class)); doAnswer(new Answer() { @Override//from w ww. j a va2 s . com public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); Object argument = arguments[arguments.length - 2]; theCapturedArgument.set((ThreadSafeRunTestResults) argument); return invocationOnMock.callRealMethod(); } }).when(slangTestRunner).splitTestCasesByRunState(any(BulkRunMode.class), anyMap(), anyList(), any(IRunTestResults.class), eq(buildModeConfig)); doAnswer(new Answer() { @Override @SuppressWarnings("unchecked") public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); capturedTestsSeq.set((Map<String, SlangTestCase>) arguments[1]); return null; } }).when(slangTestRunner).runTestsSequential(anyString(), anyMap(), anyMap(), any(IRunTestResults.class)); doAnswer(new Answer() { @Override @SuppressWarnings("unchecked") public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] arguments = invocationOnMock.getArguments(); capturedTestsPar.set((Map<String, SlangTestCase>) arguments[1]); return null; } }).when(slangTestRunner).runTestsParallel(anyString(), anyMap(), anyMap(), any(ThreadSafeRunTestResults.class)); // Tested call slangBuilder.processRunTests(projectPath, testSuites, POSSIBLY_MIXED, compiledFlows, testCases, buildModeConfig); InOrder inOrder = inOrder(slangTestRunner); inOrder.verify(slangTestRunner).splitTestCasesByRunState(eq(POSSIBLY_MIXED), eq(testCases), eq(testSuites), isA(ThreadSafeRunTestResults.class), eq(buildModeConfig)); inOrder.verify(slangTestRunner).runTestsSequential(eq(projectPath), anyMap(), eq(compiledFlows), eq(theCapturedArgument.get())); inOrder.verify(slangTestRunner).runTestsParallel(eq(projectPath), anyMap(), eq(compiledFlows), eq(theCapturedArgument.get())); final List<SlangTestCase> listSeq = newArrayList(capturedTestsSeq.get().values()); final List<SlangTestCase> listPar = newArrayList(capturedTestsPar.get().values()); assertEquals(0, ListUtils.intersection(listSeq, listPar).size()); // assures that a test is run only once assertEquals(newHashSet(testCases.values()), newHashSet(ListUtils.union(listSeq, listPar))); }
From source file:byps.test.TestRemoteServerR.java
/** * This test simulates a pause time where the client has no active long-pool * and the server tries to contact the client. * @throws RemoteException//from w w w . j av a2 s . c o m * @throws InterruptedException */ @Test public void testServerCallsClientNoActiveLongPoll() throws RemoteException, InterruptedException { log.info("testServerCallsClientNoActiveLongPoll("); final boolean[] holdClient = new boolean[] { true }; final AtomicInteger r1 = new AtomicInteger(); final AtomicInteger r2 = new AtomicInteger(); final AtomicInteger r3 = new AtomicInteger(); final AtomicReference<Throwable> ex = new AtomicReference<Throwable>(); final CountDownLatch countDown = new CountDownLatch(3); BClient_Testser client = TestUtilsHttp.createClient(1); ServerIFAsync remote = client.getServerIF(); // Provide implementation for interface ClientIF client.addRemote(new BSkeleton_ClientIF() { @Override public int incrementInt(int a) throws RemoteException { log.info("incrementInt(" + a + ")"); try { synchronized (holdClient) { while (holdClient[0]) { // (1) wait until (4) holdClient.wait(100 * 1000); } } } catch (Throwable e) { } return a + 1; } }); // (2) Trigger one client invocation to allocate the current active long-poll. // The client will receive the request and will wait in (1). remote.callClientIncrementInt(0, new BAsyncResultIgnored<Integer>()); // (3) Trigger server to invoke client. // Server will try to send requests to the client but there is no open long-poll. // Server has to wait until it receives a long-poll. internalCallClientAsync(remote, 5, r1, ex, countDown); internalCallClientAsync(remote, 6, r2, ex, countDown); internalCallClientAsync(remote, 7, r3, ex, countDown); // (4) release the long-pool hold in (1). synchronized (holdClient) { holdClient[0] = false; holdClient.notifyAll(); } // Now the server can send the pending requests from (3) // to the client. // Wait until all requests were processed. countDown.await(10, TimeUnit.SECONDS); TestUtils.assertEquals(log, "r1", 6, r1.get()); TestUtils.assertEquals(log, "r2", 7, r2.get()); TestUtils.assertEquals(log, "r3", 8, r3.get()); log.info(")testServerCallsClientNoActiveLongPoll"); }
From source file:com.igormaznitsa.zxpoly.MainForm.java
private void menuFileLoadSnapshotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuFileLoadSnapshotActionPerformed stepSemaphor.lock();/*from w w w. ja va 2s . c o m*/ try { this.board.forceResetCPUs(); this.board.resetIODevices(); final AtomicReference<FileFilter> theFilter = new AtomicReference<>(); final File selected = chooseFileForOpen("Select snapshot", this.lastSnapshotFolder, theFilter, new FormatZXP(), new FormatZ80(), new FormatSNA()); if (selected != null) { this.lastSnapshotFolder = selected.getParentFile(); try { final Snapshot selectedFilter = (Snapshot) theFilter.get(); log.info("Loading snapshot " + selectedFilter.getName()); selectedFilter.loadFromArray(this.board, this.board.getVideoController(), FileUtils.readFileToByteArray(selected)); } catch (Exception ex) { log.log(Level.WARNING, "Can't read snapshot file [" + ex.getMessage() + ']', ex); JOptionPane.showMessageDialog(this, "Can't read snapshot file [" + ex.getMessage() + ']', "Error", JOptionPane.ERROR_MESSAGE); } } } finally { stepSemaphor.unlock(); } }
From source file:com.spotify.docker.client.DefaultDockerClientTest.java
@Test public void testBuildImageId() throws Exception { final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); final AtomicReference<String> imageIdFromMessage = new AtomicReference<>(); final String returnedImageId = sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() { @Override/*w w w . j a v a 2s .co m*/ public void progress(ProgressMessage message) throws DockerException { final String imageId = message.buildImageId(); if (imageId != null) { imageIdFromMessage.set(imageId); } } }); assertThat(returnedImageId, is(imageIdFromMessage.get())); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.GetEngine.java
/** * Process all the GetOperations the server returned to us as a result of * its get() method. This is generally not called directly from users of * this library. Instead, call the get methods in the {@link Workspace} * class.//w w w.j a v a 2 s.c o m * <p> * <!-- Event Origination Info --> * <p> * This method is an <b>core event origination point</b>. The * {@link EventSource} object that accompanies each event fired by this * method describes the execution context (current thread, etc.) when and * where this method was invoked. * * @param the * workspace to process operations in (must not be <code>null</code>) * @param type * the type of process to perform on the get operations (must not be * <code>null</code>) * @param requestType * the type of request for the operations (must not be * <code>null</code>) * @param results * the array of arrays of operations the server returned. Null items * in the arrays will be skipped. Null arrays are not allowed. * @param options * options for the get operation (must not be <code>null</code>) * @param deleteUndoneAdds * if <code>true</code> adds which are undone can be deleted * @param onlineOperation * true if this is for a server workspace * @param flags * flags returned by the server when pending changes (must not be * <code>null</code>; pass ChangePendedFlags.UNKNOWN if no server * value available in your operation) * @return the status of the operation. Failure information for each item is * available inside this object. * @throws CanceledException * if the user canceled the processing through the default * {@link TaskMonitor} */ public GetStatus processGetOperations(final Workspace workspace, final ProcessType type, final RequestType requestType, final GetOperation[][] results, final GetOptions options, final boolean deleteUndoneAdds, final boolean onlineOperation, final ChangePendedFlags flags) throws CanceledException { Check.notNull(workspace, "workspace"); //$NON-NLS-1$ Check.notNull(type, "type"); //$NON-NLS-1$ Check.notNull(requestType, "requestType"); //$NON-NLS-1$ Check.notNull(results, "results"); //$NON-NLS-1$ Check.notNull(options, "options"); //$NON-NLS-1$ Check.notNull(flags, "flags"); //$NON-NLS-1$ log.debug("Set all get operations type to: " + type.toString()); //$NON-NLS-1$ int getOpsCount = 0; for (final GetOperation[] getOperations : results) { for (final GetOperation getOp : getOperations) { getOp.setProcessType(type); getOpsCount++; } } log.debug("Get operations count: " + String.valueOf(getOpsCount)); //$NON-NLS-1$ final UpdateLocalVersionQueueOptions localUpdateOptions = calculateUpdateLocalVersionOptions(workspace, type, requestType, onlineOperation); log.debug("localUpdateOptions: " + localUpdateOptions.toString()); //$NON-NLS-1$ log.debug("options: " + options.toString()); //$NON-NLS-1$ final List<ClientLocalVersionUpdate> remapUpdates = new ArrayList<ClientLocalVersionUpdate>(); if (WorkspaceLocation.LOCAL == workspace.getLocation() && options.contains(GetOptions.REMAP)) { final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace); try { log.debug("Trying to remap versions in the local workspace"); //$NON-NLS-1$ transaction.execute(new LocalVersionTransaction() { @Override public void invoke(final WorkspaceVersionTable lv) { // In a server workspace, when Remap is specified, the // local version table is updated for you when an item // is remapped. In a local workspace, the local version // table is not updated, and a GetOperation is returned // with VersionLocal set equal to VersionServer and // SourceLocalItem equal to TargetLocalItem. // VersionLocal is not actually set to that value yet. // We must update the local version table (both local // and server) in response to these GetOperations. final boolean setLastFileTimeToCheckin = workspace.getOptions() .contains(WorkspaceOptions.SET_FILE_TO_CHECKIN); for (final GetOperation[] getOperations : results) { for (final GetOperation getOp : getOperations) { if (null != getOp.getTargetLocalItem() && LocalPath.equals(getOp.getSourceLocalItem(), getOp.getTargetLocalItem()) && // Here the server is lying and telling us // VersionLocal is equal to VersionServer // even though it does not (yet). It is a // signal that this is a remap operation. getOp.getVersionLocal() == getOp.getVersionServer()) { getOp.setIgnore(true); final WorkspaceLocalItem lvExisting = lv .getByLocalItem(getOp.getTargetLocalItem()); if (null != lvExisting) { // If necessary, update the // last-modified time of the item on // disk to match the new check-in date // of the item that now occupies that // local path. if (setLastFileTimeToCheckin && !DotNETDate.MIN_CALENDAR.equals(getOp.getVersionServerDate()) && VersionControlConstants.ENCODING_FOLDER != getOp.getEncoding() && new File(getOp.getTargetLocalItem()).exists()) { try { final File targetLocalFile = new File(getOp.getTargetLocalItem()); final FileSystemAttributes attrs = FileSystemUtils.getInstance() .getAttributes(targetLocalFile); boolean restoreReadOnly = false; if (attrs.isReadOnly()) { attrs.setReadOnly(false); FileSystemUtils.getInstance().setAttributes(targetLocalFile, attrs); restoreReadOnly = true; } targetLocalFile.setLastModified( getOp.getVersionServerDate().getTimeInMillis()); if (restoreReadOnly) { attrs.setReadOnly(true); FileSystemUtils.getInstance().setAttributes(targetLocalFile, attrs); } } catch (final Exception ex) { log.warn("Error setting file time for get with remap", ex); //$NON-NLS-1$ } } remapUpdates.add(new ClientLocalVersionUpdate(getOp.getSourceServerItem(), getOp.getItemID(), getOp.getTargetLocalItem(), getOp.getVersionServer(), getOp.getVersionServerDate(), getOp.getEncoding(), lvExisting.getHashValue(), lvExisting.getLength(), lvExisting.getBaselineFileGUID(), null /* pendingChangeTargetServerItem */, getOp.getPropertyValues())); } } } } } }); } finally { try { transaction.close(); } catch (final IOException e) { throw new VersionControlException(e); } } log.debug("The remapUpdates list has been prepared"); //$NON-NLS-1$ } final WorkspaceLock wLock = workspace.lock(); try { /* * Create a BaselineFolderCollection object to speed up read * operations on the baseline folders (so that each simple operation * like creating a new baseline file, deleting a baseline file, etc. * does not require us to open/close the WP table). Then attach that * BaselineFolderCollection to the WorkspaceLock which protects this * ProcessGetOperations(). */ final AtomicReference<BaselineFolderCollection> baselineFolders = new AtomicReference<BaselineFolderCollection>(); if (workspace.getLocation() == WorkspaceLocation.LOCAL) { final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace); try { transaction.execute(new WorkspacePropertiesTransaction() { @Override public void invoke(final LocalWorkspaceProperties wp) { baselineFolders.set(new BaselineFolderCollection(workspace, wp.getBaselineFolders())); } }); } finally { try { transaction.close(); } catch (final IOException e) { throw new VersionControlException(e); } } wLock.setBaselineFolders(baselineFolders.get()); } log.debug("remapUpdates.size(): " + remapUpdates.size()); //$NON-NLS-1$ if (remapUpdates.size() > 0) { // If we have any remap update requests for the local version // table, execute them using a larger batch size than we // normally use. No file downloads are happening so these should // go through very quickly. Check.isTrue(localUpdateOptions.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER), "localUpdateOptions.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER)"); //$NON-NLS-1$ final UpdateLocalVersionQueue ulvq = new UpdateLocalVersionQueue(workspace, localUpdateOptions, wLock, 5000 /* flushTriggerLevel */, 10000 /* maximumLevel */, Integer.MAX_VALUE /* timeTriggerInMilliseconds */); try { for (final ClientLocalVersionUpdate remapUpdate : remapUpdates) { ulvq.queueUpdate(remapUpdate); } } finally { ulvq.close(); } log.debug("Local version updates have been successfully queued."); //$NON-NLS-1$ } // Now, create an object to track the state for this get operation. final AsyncGetOperation asyncOp = new AsyncGetOperation(workspace, type, requestType, options, deleteUndoneAdds, wLock, localUpdateOptions, flags, new AccountingCompletionService<WorkerStatus>(client.getUploadDownloadWorkerExecutor())); log.debug("Preparing Get Operation actions"); //$NON-NLS-1$ final GetOperation[] actions = prepareGetOperations(asyncOp, results); log.debug("Number of Get Operation actions prepared: " + actions.length); //$NON-NLS-1$ processOperations(asyncOp, actions); log.debug("All Get Operation actions have been processed."); //$NON-NLS-1$ return asyncOp.getStatus(); } catch (final CoreCancelException e) { throw new CanceledException(); } finally { if (wLock != null) { wLock.close(); } } }
From source file:com.spotify.docker.client.DefaultDockerClientTest.java
@Test public void testBuildImageIdPathToDockerFile() throws Exception { final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); final AtomicReference<String> imageIdFromMessage = new AtomicReference<>(); final String returnedImageId = sut.build(Paths.get(dockerDirectory), "test", "innerDir/innerDockerfile", new ProgressHandler() { @Override/*from w w w . java 2 s. c o m*/ public void progress(ProgressMessage message) throws DockerException { final String imageId = message.buildImageId(); if (imageId != null) { imageIdFromMessage.set(imageId); } } }); assertThat(returnedImageId, is(imageIdFromMessage.get())); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java
private Workspace[] updateWorkspaceInfoCache(final String key, final VersionControlClient client, String ownerName) {//from w ww. jav a2s .c om // Do not allow null for owner name. We do not want to put the // workspaces for every owner // into the cache. The machine may be a server with many different users // having workspaces // on it. Check.notNullOrEmpty(ownerName, "ownerName"); //$NON-NLS-1$ // Make sure we have the fully qualified owner name. ownerName = client.resolveUserUniqueName(ownerName); // We do this *before* removing the workspaces from cache in case it // throws. Workspace[] workspaces = null; if (client.isAuthorizedUser(ownerName)) { // Only add the permissions filter when ownerName is the // AuthenticatedUser. workspaces = client.queryWorkspaces(null, ownerName, getName(), WorkspacePermissions.READ.combine(WorkspacePermissions.USE)); } else { workspaces = client.queryWorkspaces(null, ownerName, getName()); } // Refresh the server GUID in case it changed somehow client.refreshServerGUID(); final List<InternalWorkspaceConflictInfo> warningList = new ArrayList<InternalWorkspaceConflictInfo>(); final List<KeyValuePair<Exception, Workspace>> errorList = new ArrayList<KeyValuePair<Exception, Workspace>>(); final Set<String> keysUpdated = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); // Make sure to add the key passed in. This way if no workspaces are // found at least we can record that nothing was found for this key. keysUpdated.add(key); synchronized (cacheMutex) { // Remove all workspaces for the specified repository. final List<WorkspaceInfo> infoRemovedList = removeCachedWorkspaceInfo(client, workspaces, false); infoRemovedList.addAll(removeCachedWorkspaceInfo(client, ownerName, false)); // Add all workspaces that are local and are owned by the specified // owner. for (final Workspace workspace : workspaces) { try { final AtomicReference<InternalWorkspaceConflictInfo[]> cws1 = new AtomicReference<InternalWorkspaceConflictInfo[]>(); final WorkspaceInfo info = getCache().insertWorkspace(workspace, cws1); for (final InternalWorkspaceConflictInfo iwci : cws1.get()) { warningList.add(iwci); } // For each workspace info that was removed, we want to copy // its local metadata (e.g., LastSavedCheckin) to the new // object. copyLocalMetadata(info, infoRemovedList); keysUpdated.addAll(createLoadWorkspacesTableKeys(client, workspace)); } catch (final VersionControlException exception) { // Skip the workspace if there's a mapping conflict, etc. errorList.add(new KeyValuePair<Exception, Workspace>(exception, workspace)); } } final AtomicReference<InternalWorkspaceConflictInfo[]> cws2 = new AtomicReference<InternalWorkspaceConflictInfo[]>(); InternalCacheLoader.saveConfigIfDirty(getCache(), cws2, cacheMutex, workspaceCacheFile); for (final InternalWorkspaceConflictInfo iwci : cws2.get()) { warningList.add(iwci); } // Record for EnsureUpdateWorkspaceInfoCache() the fact that we have // already queried the server for the user's workspaces. final Long now = System.currentTimeMillis(); for (final String updatedKey : keysUpdated) { workspacesLoadedTable.put(updatedKey, now); } } // Raise all of the error events after releasing the lock. for (final InternalWorkspaceConflictInfo iwci : warningList) { onNonFatalError(new WorkstationNonFatalErrorEvent(EventSource.newFromHere(), iwci)); } for (final KeyValuePair<Exception, Workspace> error : errorList) { onNonFatalError( new WorkstationNonFatalErrorEvent(EventSource.newFromHere(), error.getKey(), error.getValue())); } return workspaces; }