Example usage for java.lang Object notifyAll

List of usage examples for java.lang Object notifyAll

Introduction

In this page you can find the example usage for java.lang Object notifyAll.

Prototype

@HotSpotIntrinsicCandidate
public final native void notifyAll();

Source Link

Document

Wakes up all threads that are waiting on this object's monitor.

Usage

From source file:org.openengsb.connector.maven.internal.MavenServiceTest.java

private void makeNotifyAnswerForBuildStart(final Object syncFinish) {
    doAnswer(new Answer<Void>() {
        @Override// ww w.j  a  v  a 2s  .c  o m
        public Void answer(InvocationOnMock invocation) throws Throwable {
            synchronized (syncFinish) {
                syncFinish.notifyAll();
            }
            return null;
        }
    }).when(buildEvents).raiseEvent(any(BuildStartEvent.class));
}

From source file:org.rifidi.emulator.reader.command.controller.abstract_.AbstractCommandController.java

/**
 * Creates a new AbstractCommandController object with passed initial power
 * and operating states, along with a CommunicationChannel object to send
 * processed command responses to.//w w w.  j  ava  2s  .c  o m
 * 
 * @param initialPowerState
 *            The initial power state to place this controller in.
 * @param initialOperatingState
 *            The initial operating state to place this controller in.
 * @param powerControlSignal
 *            The power control signal for this AbstractCommandController to
 *            observe. If <i>null</i> is passed, this will not observe a
 *            power signal.
 * @param connectionControlSignal
 *            The connection control signal for this
 *            AbstractCommandController to observe. If <i>null</i> is
 *            passed, this will not observe a connection signal.
 * @param communication
 *            The Communication which this controller interacts with.
 */
public AbstractCommandController(CommandControllerPowerState initialPowerState,
        AbstractCommandControllerOperatingState initialOperatingState,
        ControlSignal<Boolean> powerControlSignal, ControlSignal<Boolean> connectionControlSignal,
        Communication communication) {
    /* Call the AbstractPowerModule's constructor */
    super(initialPowerState, powerControlSignal);

    logger.debug("powerstate: " + initialPowerState);
    logger.debug("cur power state: " + super.getPowerState());

    /* Assign instance variables */
    this.initialOperatingState = initialOperatingState;
    this.curOperatingState = initialOperatingState;
    this.curCommunication = communication;
    this.connectionControlSignal = connectionControlSignal;

    /* Register as connection observer */
    if (this.connectionControlSignal != null) {
        this.connectionControlSignal.addObserver(this);

    }

    /* Set wait variables to defaults */
    this.suspensionLock = new Object();
    this.interrupted = false;
    this.suspended = false;

    /* Synchronize on the passed processor's suspension lock */
    Object lock = this.getSuspensionLock();
    synchronized (lock) {
        /* Turn on interruption status */
        this.setInterrupted(true);

        /* Notify anything waiting */
        lock.notifyAll();

    }

}

From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Test//from ww  w. j a  v a2s  .co  m
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.hadoop.hdfs.TestAutoEditRollWhenAvatarFailover.java

/**
 * Test if we can get block locations after killing primary avatar,
 * failing over to standby avatar (making it the new primary),
 * restarting a new standby avatar, killing the new primary avatar and
 * failing over to the restarted standby.
 * /*from  w  w  w .  j  a v a  2s  . c o m*/
 * Write logs for a while to make sure automatic rolling are triggered.
 */
@Test
public void testDoubleFailOverWithAutomaticRoll() throws Exception {
    setUp(false, "testDoubleFailOverWithAutomaticRoll");

    // To make sure it's never the case that both primary and standby
    // issue rolling, we use a injection handler. 
    final AtomicBoolean startKeepThread = new AtomicBoolean(true);
    final AtomicInteger countAutoRolled = new AtomicInteger(0);
    final AtomicBoolean needFail = new AtomicBoolean(false);
    final AtomicLong currentThreadId = new AtomicLong(-1);
    final Object waitFor10Rolls = new Object();
    InjectionHandler.set(new InjectionHandler() {
        @Override
        protected void _processEvent(InjectionEventI event, Object... args) {
            if (event == InjectionEvent.FSEDIT_AFTER_AUTOMATIC_ROLL) {
                countAutoRolled.incrementAndGet();
                if (countAutoRolled.get() >= 10) {
                    synchronized (waitFor10Rolls) {
                        waitFor10Rolls.notifyAll();
                    }
                }

                if (!startKeepThread.get()) {
                    currentThreadId.set(-1);
                } else if (currentThreadId.get() == -1) {
                    currentThreadId.set(Thread.currentThread().getId());
                } else if (currentThreadId.get() != Thread.currentThread().getId()) {
                    LOG.warn("[Thread " + Thread.currentThread().getId() + "] expected: " + currentThreadId);
                    needFail.set(true);
                }

                LOG.info("[Thread " + Thread.currentThread().getId() + "] finish automatic log rolling, count "
                        + countAutoRolled.get());

                // Increase the rolling time a little bit once after 7 auto rolls 
                if (countAutoRolled.get() % 7 == 3) {
                    DFSTestUtil.waitNMilliSecond(75);
                }
            }
        }
    });

    FileSystem fs = cluster.getFileSystem();

    // Add some transactions during a period of time before failing over.
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 100; i++) {
        fs.setTimes(new Path("/"), 0, 0);
        DFSTestUtil.waitNMilliSecond(100);
        if (i % 10 == 0) {
            LOG.info("================== executed " + i + " queries");
        }
        if (countAutoRolled.get() >= 10) {
            LOG.info("Automatic rolled 10 times.");
            long duration = System.currentTimeMillis() - startTime;
            TestCase.assertTrue("Automatic rolled 10 times in just " + duration + " msecs, which is too short",
                    duration > 4500);
            break;
        }
    }
    TestCase.assertTrue("Only " + countAutoRolled + " automatic rolls triggered, which is lower than expected.",
            countAutoRolled.get() >= 10);

    // Tune the rolling timeout temporarily to avoid race conditions
    // only triggered in tests
    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(5000);
    cluster.getStandbyAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(5000);

    LOG.info("================== killing primary 1");

    cluster.killPrimary();

    // Fail over and make sure after fail over, automatic edits roll still
    // will happen.
    countAutoRolled.set(0);
    startKeepThread.set(false);
    currentThreadId.set(-1);
    LOG.info("================== failing over 1");
    cluster.failOver();
    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(1000);
    LOG.info("================== restarting standby");
    cluster.restartStandby();
    cluster.getStandbyAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(1000);
    LOG.info("================== Finish restarting standby");

    // Wait for automatic rolling happens if there is no new transaction.
    startKeepThread.set(true);

    startTime = System.currentTimeMillis();
    long waitDeadLine = startTime + 20000;
    synchronized (waitFor10Rolls) {
        while (System.currentTimeMillis() < waitDeadLine && countAutoRolled.get() < 10) {
            waitFor10Rolls.wait(waitDeadLine - System.currentTimeMillis());
        }
    }
    TestCase.assertTrue("Only " + countAutoRolled + " automatic rolls triggered, which is lower than expected.",
            countAutoRolled.get() >= 10);
    long duration = System.currentTimeMillis() - startTime;
    TestCase.assertTrue("Automatic rolled 10 times in just " + duration + " msecs", duration > 9000);

    // failover back 
    countAutoRolled.set(0);
    startKeepThread.set(false);
    currentThreadId.set(-1);

    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(6000);
    cluster.getStandbyAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(6000);

    LOG.info("================== killing primary 2");
    cluster.killPrimary();
    LOG.info("================== failing over 2");
    cluster.failOver();

    cluster.getPrimaryAvatar(0).avatar.namesystem.getFSImage().getEditLog().setTimeoutRollEdits(1000);

    // Make sure after failover back, automatic rolling can still happen.
    startKeepThread.set(true);

    for (int i = 0; i < 100; i++) {
        fs.setTimes(new Path("/"), 0, 0);
        DFSTestUtil.waitNMilliSecond(200);
        if (i % 10 == 0) {
            LOG.info("================== executed " + i + " queries");
        }
        if (countAutoRolled.get() > 10) {
            LOG.info("Automatic rolled 10 times.");
            duration = System.currentTimeMillis() - startTime;
            TestCase.assertTrue("Automatic rolled 10 times in just " + duration + " msecs, which is too short",
                    duration > 9000);
            break;
        }
    }
    TestCase.assertTrue("Only " + countAutoRolled + " automatic rolls triggered, which is lower than expected.",
            countAutoRolled.get() >= 10);

    InjectionHandler.clear();

    if (needFail.get()) {
        TestCase.fail("Automatic rolling doesn't happen in the same thread when should.");
    }
}

From source file:com.rapleaf.hank.ZkTestCase.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN);

    setupZkServer();/*from   ww  w . j  a  v  a  2 s. c  o  m*/

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    createNodeRecursively(zkRoot);
}

From source file:org.openengsb.connector.maven.internal.MavenServiceTest.java

@Test
public void asyncBuild_shouldRaiseBuildSuccessEvent() throws Exception {
    final Object sync = new Object();
    mavenService.setSynchronous(false);// ww w  .java  2 s.  c  om
    mavenService.setProjectPath(getPath("test-unit-success"));
    mavenService.setCommand("clean compile");
    ArgumentCaptor<BuildSuccessEvent> eventCaptor = ArgumentCaptor.forClass(BuildSuccessEvent.class);
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            synchronized (sync) {
                sync.notifyAll();
            }
            return null;
        }
    }).when(buildEvents).raiseEvent(eventCaptor.capture());
    Thread waitForBuildEnd = startWaiterThread(sync);
    mavenService.build();
    waitForBuildEnd.join();
    BuildSuccessEvent event = eventCaptor.getValue();
    assertThat(event.getOutput(), containsString("SUCCESS"));
}

From source file:edu.umn.msi.tropix.common.test.EasyMockUtilsTest.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "NN" }, justification = "Not actually mutating state.")
@Test(groups = "unit", timeOut = 1000, invocationCount = 10)
public void waitingAnswer() throws InterruptedException {
    final Foo foo = EasyMock.createMock(Foo.class);
    EasyMock.makeThreadSafe(foo, true);//from w  w w  .  java  2s.  co m
    final WaitRunnable runnable = new WaitRunnable();
    runnable.caller.foo = foo;
    final Object object = new Object();
    foo.foo();
    EasyMock.expectLastCall().andAnswer(EasyMockUtils.waitFor(object));
    EasyMock.replay(foo);
    new Thread(runnable).start();
    assert !runnable.returned;
    while (!runnable.returned) {
        synchronized (object) { // Renotify in case waiting hasn't occurred yet.
            object.notifyAll();
        }
        Thread.sleep(1);
    }
    EasyMock.verify(foo);
}

From source file:com.taobao.gecko.service.impl.GeckoHandler.java

private void addConnectionToGroup(final DefaultConnection conn, final String group, final int maxConnCount) {
    conn.getRemotingContext().addConnectionToGroup(group, conn);
    // /*from  w  ww . j  a v a2 s.c  om*/
    final Object readyLock = this.remotingController.getAttribute(group, Constants.GROUP_CONNECTION_READY_LOCK);
    if (readyLock != null) {
        // 
        synchronized (readyLock) {
            if (this.remotingController.getConnectionCount(group) >= maxConnCount) {
                readyLock.notifyAll();
            }
        }
    }
}

From source file:com.liveramp.hank.test.ZkTestCase.java

@Before
public final void setUpZk() throws Exception {

    setupZkServer();// w  ww . j a  v  a 2  s  .com

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    WaitUntil.orDie(() -> {
        try {
            return zk.exists(zkRoot, false) == null;
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    createNodeRecursively(zkRoot);
}

From source file:com.alibaba.napoli.gecko.service.impl.GeckoHandler.java

private void addConnectionToGroup(final DefaultConnection conn, final String group, final int maxConnCount) {
    conn.getRemotingContext().addConnectionToGroup(group, conn);
    // ??/*from  www.jav  a  2 s.c o m*/
    final Object readyLock = this.remotingController.getAttribute(group, Constants.GROUP_CONNECTION_READY_LOCK);
    if (readyLock != null) {
        // 
        synchronized (readyLock) {
            if (this.remotingController.getConnectionCount(group) >= maxConnCount) {
                readyLock.notifyAll();
            }
        }
    }
}