public void testEarlySet() throws InterruptedException { final BlockingCell<String> cell = new BlockingCell<String>(); final AtomicReference<String> holder = new AtomicReference<String>(); Thread getterThread = new Thread( new Runnable() { public void run() { try { Thread.sleep(300); holder.set(cell.get()); } catch (InterruptedException ie) { // no special handling required } } }); Thread setterThread = new Thread( new Runnable() { public void run() { cell.set("hello"); } }); getterThread.start(); setterThread.start(); getterThread.join(); setterThread.join(); assertEquals("hello", holder.get()); }
public void newCharacter(CharacterEvent ce) { int oldChar2type; // Previous character not typed correctly - 1 point penalty if (ce.source == generator.get()) { oldChar2type = char2type.getAndSet(ce.character); // 接收随机字母 if (oldChar2type != -1) { score.decrementAndGet(); setScore(); } } // If character is extraneous - 1 point penalty // If character does not match - 1 point penalty else if (ce.source == typist.get()) { // 在此有个假设:即正在使用的该变量值不会被变更且程序代码完成时也是如此 // 所有已经被我们设定的具有特定值的变量就应当是那个值。 while (true) { oldChar2type = char2type.get(); // 获取上次已接收到的随机字母 if (oldChar2type != ce.character) { // ce.character是用户输入的字母,现在作比较 score.decrementAndGet(); break; } else if (char2type.compareAndSet(oldChar2type, -1)) { score.incrementAndGet(); break; } } setScore(); } }
public void testGetWaitsUntilSet() throws InterruptedException { final BlockingCell<String> cell = new BlockingCell<String>(); final String value = "foo"; final AtomicReference<Object> valueHolder = new AtomicReference<Object>(); final AtomicBoolean doneHolder = new AtomicBoolean(false); Thread getterThread = new Thread() { @Override public void run() { try { valueHolder.set(cell.get()); } catch (InterruptedException ex) { fail("hit InterruptedException"); ex.printStackTrace(); } doneHolder.set(true); } }; getterThread.start(); Thread.sleep(300); assertFalse(doneHolder.get()); cell.set(value); getterThread.join(); assertTrue(doneHolder.get()); assertTrue(value == valueHolder.get()); }
/** * Asynchronous send of HTTP content. * * @param httpContent The HTTP content to send * @param callback The callback to use to notify success or failure */ public void sendContent(HttpContent httpContent, Callback callback) { if (LOG.isDebugEnabled()) LOG.debug("sendContent(http={},{})", httpContent, callback); if (BufferUtil.hasContent(_aggregate)) { callback.failed(new IOException("cannot sendContent() after write()")); return; } if (_channel.isCommitted()) { callback.failed(new IOException("committed")); return; } while (true) { switch (_state.get()) { case OPEN: if (!_state.compareAndSet(OutputState.OPEN, OutputState.PENDING)) continue; break; case ERROR: callback.failed(new EofException(_onError)); return; case CLOSED: callback.failed(new EofException("Closed")); return; default: throw new IllegalStateException(); } break; } ByteBuffer buffer = _channel.useDirectBuffers() ? httpContent.getDirectBuffer() : null; if (buffer == null) buffer = httpContent.getIndirectBuffer(); if (buffer != null) { sendContent(buffer, callback); return; } try { ReadableByteChannel rbc = httpContent.getReadableByteChannel(); if (rbc != null) { // Close of the rbc is done by the async sendContent sendContent(rbc, callback); return; } InputStream in = httpContent.getInputStream(); if (in != null) { sendContent(in, callback); return; } throw new IllegalArgumentException("unknown content for " + httpContent); } catch (Throwable th) { abort(th); callback.failed(th); } }
/** * Called to indicate that the last write has been performed. It updates the state and performs * cleanup operations. */ void closed() { while (true) { OutputState state = _state.get(); switch (state) { case CLOSED: { return; } case UNREADY: { if (_state.compareAndSet(state, OutputState.ERROR)) _writeListener.onError( _onError == null ? new EofException("Async closed") : _onError); break; } default: { if (!_state.compareAndSet(state, OutputState.CLOSED)) break; try { _channel.getResponse().closeOutput(); } catch (Throwable x) { if (LOG.isDebugEnabled()) LOG.debug(x); abort(x); } finally { releaseBuffer(); } // Return even if an exception is thrown by closeOutput(). return; } } } }
/** * Transitions to the {@code newState} if not already in that state and calls any associated event * listener. */ private void transitionTo(State newState, CheckedRunnable listener) { boolean transitioned = false; synchronized (this) { if (!getState().equals(newState)) { switch (newState) { case CLOSED: state.set(new ClosedState(this)); break; case OPEN: state.set(new OpenState(this)); break; case HALF_OPEN: state.set(new HalfOpenState(this)); break; } transitioned = true; } } if (transitioned && listener != null) { try { listener.run(); } catch (Exception ignore) { } } }
@Test public void postOneParameter() throws Exception { String value = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKQLMNOPQRSTUVWXYZ1234567809`~!@#$%^&*()_+-=,.<>/?;:'\"[]{}\\| "; final AtomicReference<String> param1Value = new AtomicReference<>(); integrationServer.addServlet( new HttpServlet() { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { param1Value.set(req.getParameter("param1")); resp.getWriter().write(okBody); resp.getWriter().flush(); } }, "/testOk"); BlockingHttpCallback httpCallback = new BlockingHttpCallback(); httpClient .createPost("http://localhost:" + port + "/testOk") .addFormParameter("param1", value) .build() .execute(httpCallback); httpCallback.waitForCompletion(); assertEquals(okBody, httpCallback.getBody()); assertEquals(200, httpCallback.getStatusCode()); assertEquals(value, param1Value.get()); }
/** * Remove all configuration values under a single section. * * @param section section name, e.g "branch" * @param subsection optional subsection value, e.g. a branch name */ public void unsetSection(String section, String subsection) { State src, res; do { src = state.get(); res = unsetSection(src, section, subsection); } while (!state.compareAndSet(src, res)); }
@Test public void reportFailureAfterTestCompleted() { AtomicReference<TestContext> testRef = new AtomicReference<>(); TestSuite suite = TestSuite.create("my_suite") .test("my_test_1", testRef::set) .test( "my_test_2", context -> { try { testRef.get().fail(); } catch (AssertionError e) { } }); TestReporter reporter = new TestReporter(); run(suite, reporter); reporter.await(); assertEquals(1, reporter.exceptions.size()); assertEquals(2, reporter.results.size()); TestResult result = reporter.results.get(0); assertEquals("my_test_1", result.name()); assertTrue(result.succeeded()); assertNull(result.failure()); result = reporter.results.get(1); assertEquals("my_test_2", result.name()); assertTrue(result.succeeded()); assertNull(result.failure()); }
private void failTest(Handler<TestContext> thrower) { AtomicReference<Throwable> failure = new AtomicReference<>(); TestSuite suite = TestSuite.create("my_suite") .test( "my_test", context -> { try { thrower.handle(context); } catch (Error | RuntimeException e) { failure.set(e); throw e; } }); TestReporter reporter = new TestReporter(); run(suite, reporter); reporter.await(); assertEquals(0, reporter.exceptions.size()); assertEquals(1, reporter.results.size()); TestResult result = reporter.results.get(0); assertEquals("my_test", result.name()); assertFalse(result.succeeded()); assertTrue(result.failed()); assertNotNull(result.failure()); assertSame(failure.get().getMessage(), result.failure().message()); assertSame(failure.get(), result.failure().cause()); }
@Test public void runTestWithFailBeforeAsync() throws Exception { AtomicReference<AssertionError> failure = new AtomicReference<>(); BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1); TestSuite suite = TestSuite.create("my_suite") .test( "my_test", context -> { try { context.fail(); } catch (AssertionError e) { failure.set(e); } queue.add(context.async()); }); TestReporter reporter = new TestReporter(); run(suite, reporter); reporter.await(); Async async = queue.poll(2, TimeUnit.SECONDS); async.complete(); assertTrue(reporter.completed()); assertEquals(0, reporter.exceptions.size()); assertEquals(1, reporter.results.size()); TestResult result = reporter.results.get(0); assertEquals("my_test", result.name()); assertFalse(result.succeeded()); assertTrue(result.failed()); assertNotNull(result.failure()); assertSame(failure.get(), result.failure().cause()); }
@Test(groups = "online") public void asyncOptionsTest() throws Exception { final AtomicReference<HttpHeaders> responseHeaders = new AtomicReference<>(); try (AsyncHttpClient c = asyncHttpClient()) { final String[] expected = {"GET", "HEAD", "OPTIONS", "POST", "TRACE"}; Future<String> f = c.prepareOptions("http://www.apache.org/") .execute( new AsyncHandlerAdapter() { @Override public State onHeadersReceived(HttpResponseHeaders content) throws Exception { responseHeaders.set(content.getHeaders()); return State.ABORT; } @Override public String onCompleted() throws Exception { return "OK"; } }); f.get(20, TimeUnit.SECONDS); HttpHeaders h = responseHeaders.get(); assertNotNull(h); String[] values = h.get(HttpHeaders.Names.ALLOW).split(",|, "); assertNotNull(values); assertEquals(values.length, expected.length); Arrays.sort(values); assertEquals(values, expected); } }
@Test public void testNegativeRequestThrowsIllegalArgumentException() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Observable.just(1, 2, 3, 4) .subscribe( new Subscriber<Integer>() { @Override public void onStart() { request(1); } @Override public void onCompleted() {} @Override public void onError(Throwable e) { exception.set(e); latch.countDown(); } @Override public void onNext(Integer t) { request(-1); request(1); } }); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(exception.get() instanceof IllegalArgumentException); }
/** * If no thread has been spawned so far, spawns a new one that will perform the cache init. * Optionally waits for the cache initialization to be performed in a another thread. */ private void useNewThreadToInitialize(boolean wait) { if (wait && isWorkspaceLockedByCurrentThread()) { // may not wait if we currently hold a conflicting rule throw new IllegalStateException( "Cannot wait for the thread to finish if we currently hold the WS lock"); } CountDownLatch myGuard = initializerGuard.get(); // check if there was already a thread scheduled if (myGuard == null) { // no guard found so far final CountDownLatch newGuard = new CountDownLatch(1); if (initializerGuard.compareAndSet(null, newGuard)) { // still no other thread created a guard in the (short) meantime myGuard = newGuard; // aquire the WS rule in an own thread and perform the initialization from there startInitializerThread(newGuard); } else { // use the guard that was created by another thread myGuard = initializerGuard.get(); } } if (myGuard == null) { throw new IllegalStateException(); } if (wait) { try { // optionally wait for the initialization to finish myGuard.await(); } catch (InterruptedException e) { // ignore } } }
private void dispatchTasks(CancellationToken cancelToken) { if (isCurrentThreadDispatching()) { // Tasks will be dispatched there. return; } Thread currentThread = Thread.currentThread(); Throwable toThrow = null; while (!isQueueEmpty()) { if (dispatcherThread.compareAndSet(null, currentThread)) { try { TaskDef taskDef = pollFromQueue(); if (taskDef != null) { taskDef.doTask(cancelToken); } } catch (Throwable ex) { // Only in a case of a very serious error (like OutOfMemory) // will this block be executed because exceptions thrown // by the task (and the cleanup task) is caught and logged. if (toThrow == null) toThrow = ex; else toThrow.addSuppressed(ex); } finally { dispatcherThread.set(null); } } else { return; } } ExceptionHelper.rethrowIfNotNull(toThrow); }
public void testConcurrentCreateAndDeleteOverTheSameConfig() { final String configName = "testconfig"; final File configDir = getFile("solr").toPath().resolve("configsets/configset-2/conf").toFile(); uploadConfig(configDir, configName); // upload config once, to be used by all collections final SolrClient solrClient = new HttpSolrClient(solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString()); final AtomicReference<Exception> failure = new AtomicReference<>(); final int timeToRunSec = 30; final Thread[] threads = new Thread[2]; for (int i = 0; i < threads.length; i++) { final String collectionName = "collection" + i; threads[i] = new CreateDeleteCollectionThread( "create-delete-" + i, collectionName, configName, timeToRunSec, solrClient, failure); } startAll(threads); joinAll(threads); assertNull("concurrent create and delete collection failed: " + failure.get(), failure.get()); try { solrClient.close(); } catch (IOException e) { throw new RuntimeException(e); } }
private static void testCallExitsOnClose( final QueueCall call, ClosableBlockingQueue<String> queue) throws Exception { final AtomicReference<Throwable> errorRef = new AtomicReference<>(); Runnable runnable = new Runnable() { @Override public void run() { try { call.call(); } catch (Throwable t) { errorRef.set(t); } } }; Thread thread = new Thread(runnable); thread.start(); Thread.sleep(100); queue.close(); thread.join(); @SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable cause = errorRef.get(); assertTrue(cause instanceof IllegalStateException); }
@Test public void testBasicSetup() { // build injector, but don't make use of it directly, only via the request processor Injector i = Guice.createInjector(new TestModule()); SampleFactory f = RequestFactorySource.create(SampleFactory.class); // final String[] holder = new String[1]; final AtomicReference<String> holder = new AtomicReference<String>(); f.initialize( new SimpleEventBus(), new RequestTransport() { public void send(String arg0, TransportReceiver arg1) { // the SIMPLE_REQUEST_PROCESSOR field should have been repopulated by guice // and any dependencies satisfied String resp = GwtRequestFactoryVisitor.SIMPLE_REQUEST_PROCESSOR.process(arg0); arg1.onTransportSuccess(resp); } }); f.req() .trim(" word ") .fire( new Receiver<String>() { @Override public void onSuccess(String arg0) { holder.set(arg0); } }); Assert.assertEquals("word", holder.get()); }
@Test public void testHeartbeat() throws IOException, ServletException { // Open connection AtmosphereRequest request = new AtmosphereRequest.Builder().pathInfo("/heartbeat").method("GET").build(); request.header(X_ATMOSPHERE_TRANSPORT, WEBSOCKET_TRANSPORT); framework.doCometSupport(request, AtmosphereResponse.newInstance()); // Check suspend final AtmosphereResource res = r.get(); assertNotNull(res); // Send heartbeat request = new AtmosphereRequest.Builder() .pathInfo("/heartbeat") .method("GET") .body(Heartbeat.paddingData) .build(); request.header(X_ATMOSPHERE_TRANSPORT, WEBSOCKET_TRANSPORT); request.setAttribute(HeartbeatInterceptor.INTERCEPTOR_ADDED, ""); res.initialize( res.getAtmosphereConfig(), res.getBroadcaster(), request, AtmosphereResponse.newInstance(), framework.getAsyncSupport(), res.getAtmosphereHandler()); request.setAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE, res); framework.doCometSupport(request, AtmosphereResponse.newInstance()); assertNotNull(message.get()); assertEquals(message.get(), Heartbeat.paddingData); }
@Subscribe public void lifecycleChanged(Lifecycle lifecycle) { LOG.debug("Lifecycle is now {}", lifecycle); // if we switch to RUNNING from STARTING (or unknown) the server is ready to accept connections // on inputs. // we want to postpone opening the inputs earlier, so we don't get swamped with messages before // we can actually process them. if ((lifecycle == Lifecycle.RUNNING) && (previousLifecycle.get() == Lifecycle.STARTING || previousLifecycle.get() == Lifecycle.UNINITIALIZED)) { LOG.info( "Triggering launching persisted inputs, node transitioned from {} to {}", previousLifecycle.get(), lifecycle); // Set lifecycle BEFORE counting down the latch to avoid race conditions! previousLifecycle.set(lifecycle); startLatch.countDown(); } // if we failed to start up due to some other service aborting, we need to get over the barrier. if (lifecycle == Lifecycle.FAILED) { startLatch.countDown(); } }
private Throwable waitFor(final AtomicReference<Throwable> reference) { while (reference.get() == null) { yield(); } return reference.get(); }
@Test public void testExceptionHandler() { final AtomicReference<Throwable> caughedException = new AtomicReference<Throwable>(); ExceptionHandler<Listener<Integer>, Integer> exceptionHandler = new ExceptionHandler<Listener<Integer>, Integer>() { @Override public void handleException(Listener<Integer> listenerKey, Integer event, Throwable e) { caughedException.set(e); } }; EventUtil<Integer, Integer, Listener<Integer>> eventUtil = new TestEventUtil(); EventDispatcher<Integer, Integer, Listener<Integer>, Listener<Integer>> eventDispatcher = new EventDispatcherImpl<Integer, Integer, Listener<Integer>, Listener<Integer>>( eventUtil, exceptionHandler); Listener<Integer> alwaysThrowsExceptionListener = new Listener<Integer>() { @Override public void receiveEvent(Integer event) { throw new RuntimeException("Dropped"); } }; eventDispatcher.addListener(alwaysThrowsExceptionListener, alwaysThrowsExceptionListener); eventDispatcher.dispatchEvent(0); Assert.assertNotNull(caughedException.get()); Assert.assertEquals("Dropped", caughedException.get().getMessage()); }
/** * Start the server running - accepting connections, receiving messages. If the server is already * running, it will not be started again. This method is designed to be called in its own thread * and will not return until the server is stopped. * * @throws RuntimeException if the server fails */ public void run() { // ensure that the server is not started twice if (!state.compareAndSet(State.STOPPED, State.RUNNING)) { started(true); return; } Selector selector = null; ServerSocketChannel server = null; try { selector = Selector.open(); server = ServerSocketChannel.open(); server.socket().bind(new InetSocketAddress(port)); server.configureBlocking(false); server.register(selector, SelectionKey.OP_ACCEPT); started(false); while (state.get() == State.RUNNING) { selector.select(100); // check every 100ms whether the server has been requested to stop for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) { SelectionKey key = it.next(); try { // remove key from the ready list it.remove(); if (key.isConnectable()) { ((SocketChannel) key.channel()).finishConnect(); } if (key.isAcceptable()) { // accept connection SocketChannel client = server.accept(); client.configureBlocking(false); client.socket().setTcpNoDelay(true); // channel is registered for further events such as read or write SelectionKey acceptKey = client.register(selector, SelectionKey.OP_READ); connection(acceptKey); } if (key.isReadable()) { for (ByteBuffer message : readIncomingMessage(key)) { messageReceived(message, key); } } } catch (IOException ioe) { resetKey(key); disconnected(key); } } } } catch (Throwable e) { throw new RuntimeException("Server failure: " + e.getMessage()); } finally { try { selector.close(); server.socket().close(); server.close(); state.set(State.STOPPED); stopped(); } catch (Exception e) { // do nothing - server failed } } }
@Test public void failedInstanceShouldReceiveCorrectCoordinatorIdUponRejoiningCluster() throws Throwable { // Given HighlyAvailableGraphDatabase initialMaster = cluster.getMaster(); // When cluster.shutdown(initialMaster); cluster.await(masterAvailable(initialMaster)); cluster.await(masterSeesSlavesAsAvailable(1)); // create node on new master to ensure that it has the greatest tx id createNodeOn(cluster.getMaster()); cluster.sync(); ClusterClient clusterClient = cleanup.add(newClusterClient(new InstanceId(1))); final AtomicReference<InstanceId> coordinatorIdWhenReJoined = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); clusterClient.addClusterListener( new ClusterListener.Adapter() { @Override public void enteredCluster(ClusterConfiguration clusterConfiguration) { coordinatorIdWhenReJoined.set(clusterConfiguration.getElected(COORDINATOR)); latch.countDown(); } }); clusterClient.init(); clusterClient.start(); // Then latch.await(2, SECONDS); assertEquals(new InstanceId(2), coordinatorIdWhenReJoined.get()); }
@Override public void flush() throws IOException { while (true) { switch (_state.get()) { case OPEN: write(BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER, false); return; case ASYNC: throw new IllegalStateException("isReady() not called"); case READY: if (!_state.compareAndSet(OutputState.READY, OutputState.PENDING)) continue; new AsyncFlush().iterate(); return; case PENDING: return; case UNREADY: throw new WritePendingException(); case ERROR: throw new EofException(_onError); case CLOSED: return; default: throw new IllegalStateException(); } } }
protected boolean fireBeforeLocationChangedFromUi(final String location) { final AtomicReference<Boolean> accept = new AtomicReference<Boolean>(); synchronized (accept) { // notify Scout Runnable t = new Runnable() { @Override public void run() { synchronized (accept) { accept.set( getScoutObject().getUIFacade().fireBeforeLocationChangedFromUI(location)); accept.notifyAll(); } } }; getUiEnvironment().invokeScoutLater(t, 0); // end notify // wait at most 10 seconds try { accept.wait(10000L); } catch (InterruptedException e) { // nop } } return accept.get() != null ? accept.get().booleanValue() : false; }
/** @see javax.servlet.ServletOutputStream#isReady() */ @Override public boolean isReady() { while (true) { switch (_state.get()) { case OPEN: return true; case ASYNC: if (!_state.compareAndSet(OutputState.ASYNC, OutputState.READY)) continue; return true; case READY: return true; case PENDING: if (!_state.compareAndSet(OutputState.PENDING, OutputState.UNREADY)) continue; return false; case UNREADY: return false; case ERROR: return true; case CLOSED: return true; default: throw new IllegalStateException(); } } }
public void unsubscribe() { Subscription s = rollingDistributionSubscription.get(); if (s != null) { s.unsubscribe(); rollingDistributionSubscription.compareAndSet(s, null); } }
public void testConcurrentCreateAndDeleteDoesNotFail() { final File configDir = getFile("solr").toPath().resolve("configsets/configset-2/conf").toFile(); final AtomicReference<Exception> failure = new AtomicReference<>(); final int timeToRunSec = 30; final Thread[] threads = new Thread[10]; for (int i = 0; i < threads.length; i++) { final String collectionName = "collection" + i; uploadConfig(configDir, collectionName); final SolrClient solrClient = new HttpSolrClient(solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString()); threads[i] = new CreateDeleteSearchCollectionThread( "create-delete-search-" + i, collectionName, collectionName, timeToRunSec, solrClient, failure); } startAll(threads); joinAll(threads); assertNull("concurrent create and delete collection failed: " + failure.get(), failure.get()); }
@Override public void schedule(final Action1<Scheduler.Inner> action) { if (innerSubscription.isUnsubscribed()) { // don't schedule, we are unsubscribed return; } final AtomicReference<Subscription> sf = new AtomicReference<Subscription>(); Subscription s = Subscriptions.from( executor.submit( new Runnable() { @Override public void run() { try { if (innerSubscription.isUnsubscribed()) { return; } action.call(_inner); } finally { // remove the subscription now that we're completed Subscription s = sf.get(); if (s != null) { innerSubscription.remove(s); } } } })); sf.set(s); innerSubscription.add(s); }