List of usage examples for java.lang Object wait
public final void wait() throws InterruptedException
From source file:org.mozilla.gecko.tests.testDistribution.java
/** * This is a hack.//from ww w . j ava 2 s .c om * * Startup results in us writing prefs -- we fetch the Distribution, which * caches its state. Our tests try to wipe those prefs, but apparently * sometimes race with startup, which leads to us not getting one of our * expected messages. The test fails. * * This hack waits for any existing background tasks -- such as the one that * writes prefs -- to finish before we begin the test. */ private void waitForBackgroundHappiness() { final Object signal = new Object(); final Runnable done = new Runnable() { @Override public void run() { synchronized (signal) { signal.notify(); } } }; synchronized (signal) { ThreadUtils.postToBackgroundThread(done); try { signal.wait(); } catch (InterruptedException e) { mAsserter.ok(false, "InterruptedException waiting on background thread.", e.toString()); } } mAsserter.dumpLog("Background task completed. Proceeding."); }
From source file:com.ngdata.hbaseindexer.util.zookeeper.ZkLock.java
/** * Try to get a lock, waits until this succeeds. * * @param lockPath path in ZooKeeper below which the ephemeral lock nodes will be created. This path should * exist prior to calling this method. * * @return a string identifying this lock, needs to be supplied to {@link ZkLock#unlock}. *//*from w ww . j av a2s . c o m*/ public static String lock(final ZooKeeperItf zk, final String lockPath) throws ZkLockException { if (zk.isCurrentThreadEventThread()) { throw new RuntimeException("ZkLock should not be used from within the ZooKeeper event thread."); } try { final long threadId = Thread.currentThread().getId(); // Quote from ZK lock recipe: // 1. Call create( ) with a pathname of "_locknode_/lock-" and the sequence and ephemeral flags set. zk.retryOperation(new ZooKeeperOperation<String>() { @Override public String execute() throws KeeperException, InterruptedException { return zk.create(lockPath + "/lock-" + threadId + "-", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); } }); while (true) { // Quote from ZK lock recipe: // 2. Call getChildren( ) on the lock node without setting the watch flag (this is important to avoid // the herd effect). List<ZkLockNode> children = parseChildren(zk.retryOperation(new ZooKeeperOperation<List<String>>() { @Override public List<String> execute() throws KeeperException, InterruptedException { return zk.getChildren(lockPath, null); } })); ZkLockNode myLockNode = null; String myLockName = null; String myLockPath = null; for (ZkLockNode child : children) { // if the child has the same thread id and session id as us, then it is our lock if (child.getThreadId() == threadId) { final String childPath = lockPath + "/" + child.getName(); Stat stat = zk.retryOperation(new ZooKeeperOperation<Stat>() { @Override public Stat execute() throws KeeperException, InterruptedException { return zk.exists(childPath, false); } }); if (stat != null && stat.getEphemeralOwner() == zk.getSessionId()) { if (myLockName != null) { // We have found another lock node which belongs to us. // This means that the lock creation above was executed twice, which can occur // in case of connection loss. Delete this node to avoid that otherwise it would // never be released. zk.retryOperation(new ZooKeeperOperation<Object>() { @Override public Object execute() throws KeeperException, InterruptedException { try { zk.delete(childPath, -1); } catch (KeeperException.NoNodeException e) { // ignore } return null; } }); } else { myLockNode = child; myLockName = child.getName(); myLockPath = childPath; } } } } if (myLockName == null) { throw new ZkLockException("Unexpected problem: did not find our lock node."); } // Idea to use SortedSets seen in a ZK recipe SortedSet<ZkLockNode> sortedChildren = new TreeSet<ZkLockNode>(children); SortedSet<ZkLockNode> lowerThanMe = sortedChildren.headSet(myLockNode); // Quote from ZK lock recipe: // 3. If the pathname created in step 1 has the lowest sequence number suffix, the client has the lock // and the client exits the protocol. if (lowerThanMe.isEmpty()) { // We have the lock return myLockPath; } // Quote from ZK lock recipe: // 4. The client calls exists( ) with the watch flag set on the path in the lock directory with the // next lowest sequence number. final String pathToWatch = lockPath + "/" + lowerThanMe.last().name; final Object condition = new Object(); final MyWatcher watcher = new MyWatcher(pathToWatch, condition); Stat stat = zk.retryOperation(new ZooKeeperOperation<Stat>() { @Override public Stat execute() throws KeeperException, InterruptedException { return zk.exists(pathToWatch, watcher); } }); if (stat == null) { // Quote from ZK lock recipe: // 5a. if exists( ) returns false, go to step 2. // This means (I think) that the lock was removed (explicitly or through session expiration) between // the moment we queried for the children and the moment we called exists() // If the node does not exist, the watcher will still be left, does not seem so tidy, hopefully // this situation does not occur often. // Let's log it to keep an eye on it LogFactory.getLog(ZkLock.class).warn("Next lower lock node does not exist: " + pathToWatch); } else { // Quote from ZK lock recipe: // 5b. Otherwise, wait for a notification for the pathname from the previous step before going // to step 2. synchronized (condition) { while (!watcher.gotNotified) { condition.wait(); } } } } } catch (Throwable t) { throw new ZkLockException("Error obtaining lock, path: " + lockPath, t); } }
From source file:org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer.java
@Override public void run(SourceContext<T> sourceContext) throws Exception { if (fetcher != null) { fetcher.run(sourceContext, valueDeserializer, lastOffsets); } else {/*from ww w . j av a 2 s.c o m*/ // this source never completes final Object waitLock = new Object(); while (running) { // wait until we are canceled try { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (waitLock) { waitLock.wait(); } } catch (InterruptedException e) { // do nothing, check our "running" status } } } // close the context after the work was done. this can actually only // happen when the fetcher decides to stop fetching sourceContext.close(); }
From source file:it.anyplace.sync.bep.IndexFinder.java
public SearchCompletedEvent doSearch(final String term) throws InterruptedException { final Object lock = new Object(); final AtomicReference<SearchCompletedEvent> reference = new AtomicReference<>(); final Object eventListener = new Object() { @Subscribe/*w ww.j a va 2 s. c om*/ public void handleSearchCompletedEvent(SearchCompletedEvent event) { if (equal(event.getQuery(), term)) { synchronized (lock) { reference.set(event); lock.notify(); } } } }; synchronized (lock) { eventBus.register(eventListener); submitSearch(term); try { while (!Thread.currentThread().isInterrupted() && reference.get() == null) { lock.wait(); } checkNotNull(reference.get()); return reference.get(); } finally { eventBus.unregister(eventListener); } } }
From source file:org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumerBase.java
@Override public void run(SourceContext<T> sourceContext) throws Exception { if (subscribedPartitionsToStartOffsets == null) { throw new Exception("The partitions were not set for the consumer"); }/*w w w. j av a2s. c o m*/ // we need only do work, if we actually have partitions assigned if (!subscribedPartitionsToStartOffsets.isEmpty()) { // create the fetcher that will communicate with the Kafka brokers final AbstractFetcher<T, ?> fetcher = createFetcher(sourceContext, subscribedPartitionsToStartOffsets, periodicWatermarkAssigner, punctuatedWatermarkAssigner, (StreamingRuntimeContext) getRuntimeContext(), offsetCommitMode); // publish the reference, for snapshot-, commit-, and cancel calls // IMPORTANT: We can only do that now, because only now will calls to // the fetchers 'snapshotCurrentState()' method return at least // the restored offsets this.kafkaFetcher = fetcher; if (!running) { return; } // (3) run the fetcher' main work method fetcher.runFetchLoop(); } else { // this source never completes, so emit a Long.MAX_VALUE watermark // to not block watermark forwarding sourceContext.emitWatermark(new Watermark(Long.MAX_VALUE)); // wait until this is canceled final Object waitLock = new Object(); while (running) { try { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (waitLock) { waitLock.wait(); } } catch (InterruptedException e) { if (!running) { // restore the interrupted state, and fall through the loop Thread.currentThread().interrupt(); } } } } }
From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") @Test//from w ww . jav a 2s. com public void testMulti() throws Exception { final String PATH = "/queue"; final int CLIENT_QTY = 4; final int MAX_ITEMS = 10; final int ADD_ITEMS = MAX_ITEMS * 100; final int SLOP_FACTOR = 2; final QueueConsumer<String> consumer = new QueueConsumer<String>() { @Override public void consumeMessage(String message) throws Exception { Thread.sleep(10); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; final Timing timing = new Timing(); final ExecutorService executor = Executors.newCachedThreadPool(); ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executor); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().forPath(PATH); final CountDownLatch isWaitingLatch = new CountDownLatch(1); final AtomicBoolean isDone = new AtomicBoolean(false); final List<Integer> counts = new CopyOnWriteArrayList<Integer>(); final Object lock = new Object(); executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { synchronized (lock) { lock.notifyAll(); } } }; while (!Thread.currentThread().isInterrupted() && client.isStarted() && !isDone.get()) { synchronized (lock) { int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size(); counts.add(size); isWaitingLatch.countDown(); lock.wait(); } } return null; } }); isWaitingLatch.await(); for (int i = 0; i < CLIENT_QTY; ++i) { final int index = i; completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { CuratorFramework client = null; DistributedQueue<String> queue = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor) .maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue(); queue.start(); for (int i = 0; i < ADD_ITEMS; ++i) { queue.put("" + index + "-" + i); } } finally { IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } return null; } }); } for (int i = 0; i < CLIENT_QTY; ++i) { completionService.take().get(); } isDone.set(true); synchronized (lock) { lock.notifyAll(); } for (int count : counts) { Assert.assertTrue(counts.toString(), count <= (MAX_ITEMS * SLOP_FACTOR)); } } finally { executor.shutdownNow(); IOUtils.closeQuietly(client); } }
From source file:org.apache.nifi.cluster.coordination.http.replication.TestThreadPoolRequestReplicator.java
@Test(timeout = 5000) public void testMonitorNotifiedOnException() { withReplicator(replicator -> {/*from w w w.ja v a 2 s . c o m*/ final Object monitor = new Object(); final CountDownLatch preNotifyLatch = new CountDownLatch(1); final CountDownLatch postNotifyLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { synchronized (monitor) { while (true) { // If monitor is not notified, this will block indefinitely, and the test will timeout try { preNotifyLatch.countDown(); monitor.wait(); break; } catch (InterruptedException e) { continue; } } postNotifyLatch.countDown(); } } }).start(); // wait for the background thread to notify that it is synchronized on monitor. preNotifyLatch.await(); try { // set the user final Authentication authentication = new NiFiAuthenticationToken( new NiFiUserDetails(StandardNiFiUser.ANONYMOUS)); SecurityContextHolder.getContext().setAuthentication(authentication); // ensure the proxied entities header is set final Map<String, String> updatedHeaders = new HashMap<>(); replicator.addProxiedEntitiesHeader(updatedHeaders); // Pass in Collections.emptySet() for the node ID's so that an Exception is thrown replicator.replicate(Collections.emptySet(), "GET", new URI("localhost:8080/nifi"), Collections.emptyMap(), updatedHeaders, true, null, true, true, monitor); Assert.fail("replicate did not throw IllegalArgumentException"); } catch (final IllegalArgumentException iae) { // expected } // wait for monitor to be notified. postNotifyLatch.await(); }); }
From source file:org.apache.nifi.cluster.coordination.http.replication.TestThreadPoolRequestReplicator.java
@Test(timeout = 5000) public void testMonitorNotifiedOnSuccessfulCompletion() { withReplicator(replicator -> {//ww w . j a v a 2 s. c o m final Object monitor = new Object(); final CountDownLatch preNotifyLatch = new CountDownLatch(1); final CountDownLatch postNotifyLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { synchronized (monitor) { while (true) { // If monitor is not notified, this will block indefinitely, and the test will timeout try { preNotifyLatch.countDown(); monitor.wait(); break; } catch (InterruptedException e) { continue; } } postNotifyLatch.countDown(); } } }).start(); // wait for the background thread to notify that it is synchronized on monitor. preNotifyLatch.await(); final Set<NodeIdentifier> nodeIds = new HashSet<>(); final NodeIdentifier nodeId = new NodeIdentifier("1", "localhost", 8000, "localhost", 8001, "localhost", 8002, 8003, false); nodeIds.add(nodeId); final URI uri = new URI("http://localhost:8080/processors/1"); final Entity entity = new ProcessorEntity(); // set the user final Authentication authentication = new NiFiAuthenticationToken( new NiFiUserDetails(StandardNiFiUser.ANONYMOUS)); SecurityContextHolder.getContext().setAuthentication(authentication); // ensure the proxied entities header is set final Map<String, String> updatedHeaders = new HashMap<>(); replicator.addProxiedEntitiesHeader(updatedHeaders); replicator.replicate(nodeIds, HttpMethod.GET, uri, entity, updatedHeaders, true, null, true, true, monitor); // wait for monitor to be notified. postNotifyLatch.await(); }); }
From source file:org.apache.nifi.cluster.coordination.http.replication.TestThreadPoolRequestReplicator.java
@Test(timeout = 5000) public void testMonitorNotifiedOnFailureResponse() { withReplicator(replicator -> {/*w w w . j a v a2 s. com*/ final Object monitor = new Object(); final CountDownLatch preNotifyLatch = new CountDownLatch(1); final CountDownLatch postNotifyLatch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { synchronized (monitor) { while (true) { // If monitor is not notified, this will block indefinitely, and the test will timeout try { preNotifyLatch.countDown(); monitor.wait(); break; } catch (InterruptedException e) { continue; } } postNotifyLatch.countDown(); } } }).start(); // wait for the background thread to notify that it is synchronized on monitor. preNotifyLatch.await(); final Set<NodeIdentifier> nodeIds = new HashSet<>(); final NodeIdentifier nodeId = new NodeIdentifier("1", "localhost", 8000, "localhost", 8001, "localhost", 8002, 8003, false); nodeIds.add(nodeId); final URI uri = new URI("http://localhost:8080/processors/1"); final Entity entity = new ProcessorEntity(); // set the user final Authentication authentication = new NiFiAuthenticationToken( new NiFiUserDetails(StandardNiFiUser.ANONYMOUS)); SecurityContextHolder.getContext().setAuthentication(authentication); // ensure the proxied entities header is set final Map<String, String> updatedHeaders = new HashMap<>(); replicator.addProxiedEntitiesHeader(updatedHeaders); replicator.replicate(nodeIds, HttpMethod.GET, uri, entity, updatedHeaders, true, null, true, true, monitor); // wait for monitor to be notified. postNotifyLatch.await(); }, Status.INTERNAL_SERVER_ERROR, 0L, null); }
From source file:org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator.java
@Override public AsyncClusterResponse replicate(Set<NodeIdentifier> nodeIds, String method, URI uri, Object entity, Map<String, String> headers, final boolean indicateReplicated, final boolean performVerification) { final Map<String, String> updatedHeaders = new HashMap<>(headers); updatedHeaders.put(RequestReplicator.CLUSTER_ID_GENERATION_SEED_HEADER, ComponentIdGenerator.generateId().toString()); if (indicateReplicated) { updatedHeaders.put(RequestReplicator.REPLICATION_INDICATOR_HEADER, "true"); }//from ww w . jav a 2 s. co m // include the proxied entities header updateRequestHeaders(updatedHeaders); if (indicateReplicated) { // If we are replicating a request and indicating that it is replicated, then this means that we are // performing an action, rather than simply proxying the request to the cluster coordinator. In this case, // we need to ensure that we use proper locking. We don't want two requests modifying the flow at the same // time, so we use a write lock if the request is mutable and a read lock otherwise. final Lock lock = isMutableRequest(method, uri.getPath()) ? writeLock : readLock; logger.debug("Obtaining lock {} in order to replicate request {} {}", lock, method, uri); lock.lock(); try { logger.debug("Lock {} obtained in order to replicate request {} {}", lock, method, uri); // Unlocking of the lock is performed within the replicate method, as we need to ensure that it is unlocked only after // the entire request has completed. final Object monitor = new Object(); synchronized (monitor) { final AsyncClusterResponse response = replicate(nodeIds, method, uri, entity, updatedHeaders, performVerification, null, !performVerification, true, monitor); try { monitor.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return response; } } finally { lock.unlock(); logger.debug("Unlocked {} after replication completed for {} {}", lock, method, uri); } } else { return replicate(nodeIds, method, uri, entity, updatedHeaders, performVerification, null, !performVerification, true, null); } }