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.limewire.mojito.db.DHTValueTest.java

public void testLocationCount() throws Exception {
    int k = KademliaSettings.REPLICATION_PARAMETER.getValue();

    Map<KUID, MojitoDHT> dhts = Collections.emptyMap();
    try {/*www . j a v  a  2 s .c  om*/
        dhts = MojitoUtils.createBootStrappedDHTsMap(2);
        Thread.sleep(250);

        KUID key = KUID.createRandomID();
        DHTValueType type = DHTValueType.TEST;
        Version version = Version.ZERO;
        byte[] b = StringUtils.toUTF8Bytes("Hello World");

        long time = System.currentTimeMillis();

        Context context = (Context) dhts.values().iterator().next();

        final Object lock = new Object();
        final Storable storable = new Storable(key, new DHTValueImpl(type, version, b));

        // Pre-Condition
        assertEquals(0, storable.getLocationCount());
        assertEquals(0L, storable.getPublishTime());
        assertTrue(DatabaseUtils.isPublishingRequired(storable));

        // Store...
        DHTFuture<StoreResult> future = context.store(storable);
        future.addDHTFutureListener(new DHTFutureAdapter<StoreResult>() {
            @Override
            public void handleFutureSuccess(StoreResult result) {
                storable.handleStoreResult(result);
                synchronized (lock) {
                    lock.notifyAll();
                }
            }
        });

        future.get();
        synchronized (lock) {
            if (storable.getLocationCount() == 0L) {
                lock.wait(1000L);
            }
        }

        // Post-Condition
        assertEquals(k, storable.getLocationCount());
        assertGreaterThanOrEquals(time, storable.getPublishTime());
        assertFalse(DatabaseUtils.isPublishingRequired(storable));

    } finally {
        for (MojitoDHT dht : dhts.values()) {
            dht.close();
        }
    }
}

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 waitAndReturnAnswer() throws InterruptedException {
    final Bar bar = EasyMock.createMock(Bar.class);
    final BarRunnable runnable = new BarRunnable();
    runnable.caller.bar = bar;//from  ww w .j  a va 2s .co  m
    final Object object = new Object();

    synchronized (object) {
        EasyMock.expect(bar.bar()).andAnswer(EasyMockUtils.waitForAndReturn(object, "Moo"));
    }
    EasyMock.replay(bar);
    new Thread(runnable).start();
    Thread.sleep(10);
    assert runnable.value == null;
    while (runnable.value == null) {
        synchronized (object) { // Renotify in case waiting hasn't occurred yet.
            object.notifyAll();
        }
        Thread.sleep(1);
    }
    assert runnable.getValue().equals("Moo");
    EasyMock.verify(bar);
}

From source file:fi.solita.phantomrunner.jetty.PhantomWebSocketHandler.java

public JsonNode sendMessageToConnections(String msg) {
    try {/*from w w  w  . java 2s.  c o  m*/
        final Object requestLock = new Object();
        final AtomicReference<JsonNode> result = new AtomicReference<JsonNode>();

        synchronized (socketLock) {
            if (socket.get() == null) {
                // wait for 10 secs for the socket to open
                socketLock.wait(TimeUnit.SECONDS.toMillis(10));
            }
        }

        if (socket.get() == null) {
            throw new PhantomWebSocketException("No open websocket connection available, cannot send message");
        }

        try {
            socket.get().send(msg, new PhantomMessageListener() {
                @Override
                public void message(JsonNode readTree) {
                    synchronized (requestLock) {
                        result.set(readTree);
                        requestLock.notifyAll();
                    }
                }
            });
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        synchronized (requestLock) {
            requestLock.wait(10000);
        }

        return result.get();
    } catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
}

From source file:com.laxser.blitz.BlitzFilter.java

protected void supportsBlitzpipe(final HttpServletRequest httpRequest) {
    // ?Blitzpipe??Blitzpipe"Cannot forward after response has been committed"
    // @see net.paoding.Blitz.web.portal.impl.PortalWaitInterceptor
    Object window = httpRequest.getAttribute(BlitzConstants.WINDOW_ATTR);
    if (window != null && window.getClass().getName().startsWith("com.laxser.blitz.web.portal")) {
        httpRequest.setAttribute(BlitzConstants.PIPE_WINDOW_IN, Boolean.TRUE);
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("notify window '" + httpRequest.getAttribute("$$blitz-portal.window.name") + "'");
            } catch (Exception e) {
                logger.error("", e);
            }/*from  w  w  w  . j av  a 2  s  .  com*/
        }
        synchronized (window) {
            window.notifyAll();
        }
    }
}

From source file:net.paoding.rose.RoseFilter.java

protected void supportsRosepipe(final HttpServletRequest httpRequest) {
    // ?rosepipe??rosepipe"Cannot forward after response has been committed"
    // @see net.paoding.rose.web.portal.impl.PortalWaitInterceptor
    Object window = httpRequest.getAttribute(RoseConstants.WINDOW_ATTR);
    if (window != null && window.getClass().getName().startsWith("net.paoding.rose.web.portal")) {
        httpRequest.setAttribute(RoseConstants.PIPE_WINDOW_IN, Boolean.TRUE);
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("notify window '" + httpRequest.getAttribute("$$paoding-rose-portal.window.name")
                        + "'");
            } catch (Exception e) {
                logger.error("", e);
            }/* w  w  w  . ja  v a 2 s .  c  o  m*/
        }
        synchronized (window) {
            window.notifyAll();
        }
    }
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

/**
 * @return max and ave send time//from   w  w  w  .ja  v  a  2  s .c om
 * @throws Exception
 */
private double[] produceMessages(Destination destination, final int toSend, final int numIterations,
        Session session, MessageProducer producer, Object addConsumerSignal) throws Exception {
    long start;
    long count = 0;
    double batchMax = 0, max = 0, sum = 0;
    for (int i = 0; i < numIterations; i++) {
        start = System.currentTimeMillis();
        for (int j = 0; j < toSend; j++) {
            long singleSendstart = System.currentTimeMillis();
            TextMessage msg = createTextMessage(session, "" + j);
            // rotate
            int priority = ((int) count % 10);
            producer.send(msg, DeliveryMode.PERSISTENT, priority, 0);
            max = Math.max(max, (System.currentTimeMillis() - singleSendstart));
            if (++count % 500 == 0) {
                if (addConsumerSignal != null) {
                    synchronized (addConsumerSignal) {
                        addConsumerSignal.notifyAll();
                        LOG.info("Signalled add consumer");
                    }
                }
            }
            ;
            if (count % 5000 == 0) {
                LOG.info("Sent " + count + ", singleSendMax:" + max);
            }

        }
        long duration = System.currentTimeMillis() - start;
        batchMax = Math.max(batchMax, duration);
        sum += duration;
        LOG.info("Iteration " + i + ", sent " + toSend + ", time: " + duration + ", batchMax:" + batchMax
                + ", singleSendMax:" + max);
    }

    LOG.info("Sent: " + toSend * numIterations + ", batchMax: " + batchMax + " singleSendMax: " + max);
    return new double[] { batchMax, sum / numIterations };
}

From source file:com.sinosoft.one.mvc.MvcFilter.java

protected void supportsMvcpipe(final HttpServletRequest httpRequest) {
    // ?mvcpipe??mvcpipe"Cannot forward after response has been committed"
    // @see com.sinosoft.one.mvc.web.portal.impl.PortalWaitInterceptor

    //        String windowNames = (String)httpRequest.getAttribute(MvcConstants.WINDOW_ATTR+".names");
    String windowName = (String) httpRequest.getAttribute(MvcConstants.WINDOW_ATTR + ".name");
    if (StringUtils.isNotBlank(windowName)) {

        Object window = httpRequest.getAttribute(MvcConstants.WINDOW_ATTR + "." + windowName);

        if (window != null && window.getClass().getName().startsWith("com.sinosoft.one.mvc.web.portal")) {
            httpRequest.setAttribute(MvcConstants.PIPE_WINDOW_IN, Boolean.TRUE);
            if (logger.isDebugEnabled()) {
                try {
                    logger.debug(//  www . j a v  a 2 s .  c o m
                            "notify window '" + httpRequest.getAttribute("$$one-mvc-portal.window.name") + "'");
                } catch (Exception e) {
                    logger.error("", e);
                }
            }
            synchronized (window) {
                window.notifyAll();
                httpRequest.removeAttribute(MvcConstants.WINDOW_ATTR + ".name");
            }
        }
    }
    // Object window = httpRequest.getAttribute(MvcConstants.WINDOW_ATTR);

}

From source file:it.anyplace.sync.bep.BlockExchangeConnectionHandler.java

public BlockExchangeConnectionHandler connect() throws Exception {
    checkNotClosed();/*from w w  w .j a v  a  2  s. c om*/
    checkArgument(socket == null && !isConnected, "already connected!");
    logger.info("connecting to {}", address.getAddress());

    KeystoreHandler keystoreHandler = KeystoreHandler.newLoader().loadAndStore(configuration);

    try {
        switch (address.getType()) {
        case TCP:
            logger.debug("opening tcp ssl connection");
            socket = keystoreHandler.createSocket(address.getSocketAddress(), BEP);
            break;
        case RELAY: {
            logger.debug("opening relay connection");
            socket = keystoreHandler.wrapSocket(new RelayClient(configuration).openRelayConnection(address),
                    BEP);
            break;
        }
        case HTTP_RELAY:
        case HTTPS_RELAY: {
            logger.debug("opening http relay connection");
            socket = keystoreHandler.wrapSocket(new HttpRelayClient(configuration).openRelayConnection(address),
                    BEP);
            break;
        }
        default:
            throw new UnsupportedOperationException("unsupported address type = " + address.getType());
        }
        in = new DataInputStream(socket.getInputStream());
        out = new DataOutputStream(socket.getOutputStream());

        sendHelloMessage(BlockExchageProtos.Hello.newBuilder().setClientName(configuration.getClientName())
                .setClientVersion(configuration.getClientVersion()).setDeviceName(configuration.getDeviceName())
                .build().toByteArray());
        markActivityOnSocket();

        BlockExchageProtos.Hello hello = receiveHelloMessage();
        logger.trace("received hello message = {}", hello);
        connectionInfo = new ConnectionInfo();
        connectionInfo.setClientName(hello.getClientName());
        connectionInfo.setClientVersion(hello.getClientVersion());
        connectionInfo.setDeviceName(hello.getDeviceName());
        logger.info("connected to device = {}", connectionInfo);
        keystoreHandler.checkSocketCerificate((SSLSocket) socket, address.getDeviceId());
        {
            ClusterConfig.Builder clusterConfigBuilder = ClusterConfig.newBuilder();
            for (String folder : configuration.getFolderNames()) {
                Folder.Builder folderBuilder = clusterConfigBuilder.addFoldersBuilder().setId(folder);
                {
                    //our device
                    Device.Builder deviceBuilder = folderBuilder.addDevicesBuilder()
                            .setId(ByteString.copyFrom(deviceIdStringToHashData(configuration.getDeviceId())));
                    if (indexHandler != null) {
                        deviceBuilder.setIndexId(indexHandler.getSequencer().indexId())
                                .setMaxSequence(indexHandler.getSequencer().currentSequence());
                    }
                }
                {
                    //other device
                    Device.Builder deviceBuilder = folderBuilder.addDevicesBuilder()
                            .setId(ByteString.copyFrom(deviceIdStringToHashData(address.getDeviceId())));
                    if (indexHandler != null) {
                        IndexInfo indexSequenceInfo = indexHandler.getIndexRepository()
                                .findIndexInfoByDeviceAndFolder(address.getDeviceId(), folder);
                        if (indexSequenceInfo != null) {
                            deviceBuilder.setIndexId(indexSequenceInfo.getIndexId())
                                    .setMaxSequence(indexSequenceInfo.getLocalSequence());
                            logger.info(
                                    "send delta index info device = {} index = {} max (local) sequence = {}",
                                    indexSequenceInfo.getDeviceId(), indexSequenceInfo.getIndexId(),
                                    indexSequenceInfo.getLocalSequence());
                        }
                    }
                }
                //TODO other devices??
            }
            sendMessage(clusterConfigBuilder.build());
        }
        final Object clusterConfigWaitingLock = new Object();
        synchronized (clusterConfigWaitingLock) {
            Object listener = new Object() {
                @Subscribe
                public void handleClusterConfigMessageProcessedEvent(ClusterConfigMessageProcessedEvent event) {
                    synchronized (clusterConfigWaitingLock) {
                        clusterConfigWaitingLock.notifyAll();
                    }
                }

                @Subscribe
                public void handleConnectionClosedEvent(ConnectionClosedEvent event) {
                    synchronized (clusterConfigWaitingLock) {
                        clusterConfigWaitingLock.notifyAll();
                    }
                }
            };
            eventBus.register(listener);
            startMessageListenerService();
            while (clusterConfigInfo == null && !isClosed()) {
                logger.debug("wait for cluster config");
                clusterConfigWaitingLock.wait();
            }
            checkNotNull(clusterConfigInfo, "unable to retrieve cluster config from peer!");
            eventBus.unregister(listener);
        }
        for (String folder : configuration.getFolderNames()) {
            if (hasFolder(folder)) {
                sendIndexMessage(folder);
            }
        }
        periodicExecutorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                sendPing();
            }
        }, 90, 90, TimeUnit.SECONDS);
    } catch (Exception ex) {
        close();
        throw ex;
    }
    isConnected = true;
    return this;
}

From source file:org.gridgain.grid.kernal.managers.eventstorage.GridEventStorageManager.java

/**
 * @param p Grid event predicate./*w  ww  .  j  a va 2s  .com*/
 * @param nodes Collection of nodes.
 * @param timeout Maximum time to wait for result, if {@code 0}, then wait until result is received.
 * @return Collection of events.
 * @throws GridException Thrown in case of any errors.
 */
@SuppressWarnings({ "SynchronizationOnLocalVariableOrMethodParameter", "deprecation" })
private List<GridEvent> query(GridPredicate<? super GridEvent> p, Collection<? extends GridNode> nodes,
        long timeout) throws GridException {
    assert p != null;
    assert nodes != null;

    if (nodes.isEmpty()) {
        U.warn(log, "Failed to query events for empty nodes collection.");

        return Collections.emptyList();
    }

    GridIoManager ioMgr = ctx.io();

    final List<GridEvent> evts = new ArrayList<GridEvent>();

    final AtomicReference<Throwable> err = new AtomicReference<Throwable>(null);

    final Set<UUID> uids = new HashSet<UUID>();

    final Object qryMux = new Object();

    for (GridNode node : nodes)
        uids.add(node.id());

    GridLocalEventListener evtLsnr = new GridLocalEventListener() {
        @Override
        public void onEvent(GridEvent evt) {
            assert evt instanceof GridDiscoveryEvent;

            synchronized (qryMux) {
                uids.remove(((GridDiscoveryEvent) evt).eventNodeId());

                if (uids.isEmpty()) {
                    qryMux.notifyAll();
                }
            }
        }
    };

    GridMessageListener resLsnr = new GridMessageListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onMessage(UUID nodeId, Object msg) {
            assert nodeId != null;
            assert msg != null;

            if (!(msg instanceof GridEventStorageMessage)) {
                U.error(log, "Received unknown message: " + msg);

                return;
            }

            GridEventStorageMessage res = (GridEventStorageMessage) msg;

            synchronized (qryMux) {
                if (uids.remove(nodeId)) {
                    if (res.events() != null)
                        evts.addAll(res.events());
                } else
                    U.warn(log,
                            "Received duplicate response (ignoring) [nodeId=" + nodeId + ", msg=" + res + ']');

                if (res.exception() != null)
                    err.set(res.exception());

                if (uids.isEmpty() || err.get() != null)
                    qryMux.notifyAll();
            }
        }
    };

    String resTopic = TOPIC_EVENT.name(UUID.randomUUID());

    try {
        addLocalEventListener(evtLsnr, new int[] { EVT_NODE_LEFT, EVT_NODE_FAILED });

        ioMgr.addMessageListener(resTopic, resLsnr);

        GridByteArrayList serFilter = U.marshal(ctx.config().getMarshaller(), p);

        GridDeployment dep = ctx.deploy().deploy(p.getClass(), U.detectClassLoader(p.getClass()));

        if (dep == null)
            throw new GridDeploymentException("Failed to deploy event filter: " + p);

        Serializable msg = new GridEventStorageMessage(resTopic, serFilter, p.getClass().getName(),
                dep.classLoaderId(), dep.deployMode(), dep.sequenceNumber(), dep.userVersion(),
                dep.participants());

        ioMgr.send(nodes, TOPIC_EVENT, msg, PUBLIC_POOL);

        if (timeout == 0)
            timeout = Long.MAX_VALUE;

        long now = System.currentTimeMillis();

        // Account for overflow of long value.
        long endTime = now + timeout <= 0 ? Long.MAX_VALUE : now + timeout;

        long delta = timeout;

        Collection<UUID> uidsCp = null;

        synchronized (qryMux) {
            try {
                while (!uids.isEmpty() && err.get() == null && delta > 0) {
                    qryMux.wait(delta);

                    delta = endTime - System.currentTimeMillis();
                }
            } catch (InterruptedException e) {
                throw new GridException("Got interrupted while waiting for event query responses.", e);
            }

            if (err.get() != null)
                throw new GridException("Failed to query events due to exception on remote node.", err.get());

            if (!uids.isEmpty())
                uidsCp = new LinkedList<UUID>(uids);
        }

        // Outside of synchronization.
        if (uidsCp != null) {
            for (Iterator<UUID> iter = uidsCp.iterator(); iter.hasNext();)
                // Ignore nodes that have left the grid.
                if (ctx.discovery().node(iter.next()) == null)
                    iter.remove();

            if (!uidsCp.isEmpty())
                throw new GridException(
                        "Failed to receive event query response from following nodes: " + uidsCp);
        }
    } finally {
        ioMgr.removeMessageListener(resTopic, resLsnr);

        removeLocalEventListener(evtLsnr);
    }

    return evts;
}

From source file:org.silverpeas.core.persistence.jdbc.JdbcSqlQueryIT.java

@SuppressWarnings("UnusedDeclaration")
private List<String> executeMultiThreadedOperations(final boolean rollbackInTransaction) throws Exception {
    final Object monitorOfDeletion = new Object();
    final Object monitorOfVerification = new Object();
    assertThat(getTableLines(), hasSize((int) NB_ROW_AT_BEGINNING));
    final List<String> result = new ArrayList<>();
    Thread deletionProcess = new Thread(() -> {
        try {/*from   ww w. ja v  a 2s. c  o  m*/
            Transaction.performInOne(() -> {
                try (final Connection connection = dbSetupRule.getSafeConnectionFromDifferentThread()) {
                    Transaction.performInOne(() -> {
                        try (Connection otherConnection = dbSetupRule.getSafeConnectionFromDifferentThread()) {
                            // Just opening two connections for pleasure :-)
                            Thread.sleep(50);
                            synchronized (monitorOfVerification) {
                                info(result, "DELETION PROCESS - In transaction");
                                info(result, "DELETION PROCESS - Waiting for verification");
                                monitorOfVerification.notifyAll();
                            }
                            synchronized (monitorOfDeletion) {
                                monitorOfDeletion.wait(500);
                            }
                            Thread.sleep(10);
                            synchronized (monitorOfVerification) {
                                assertThat(createDeleteFor("a_table").execute(), is(NB_ROW_AT_BEGINNING));
                                info(result, "DELETION PROCESS - Waiting for verification (lines deleted)");
                                monitorOfVerification.notifyAll();
                            }
                            synchronized (monitorOfDeletion) {
                                monitorOfDeletion.wait(500);
                            }
                            Thread.sleep(10);
                        }
                        return null;
                    });
                }
                assertThat(getTableLines(), hasSize(0));
                if (rollbackInTransaction) {
                    info(result, "DELETION PROCESS - Perform rollback");
                    throw new IllegalArgumentException();
                }
                return null;
            });
        } catch (Exception e) {
            info(result, "DELETION PROCESS - Rollback performed");
        }
        synchronized (monitorOfVerification) {
            info(result, "DELETION PROCESS - Transaction closed");
            monitorOfVerification.notifyAll();
        }
    });
    Thread deletionVerifications = new Thread(() -> {
        try {
            synchronized (monitorOfVerification) {
                monitorOfVerification.wait(500);
            }
            Thread.sleep(10);
            synchronized (monitorOfDeletion) {
                info(result, "VERIFICATION PROCESS - BEFORE DELETION - " + getTableLines().size() + " line(s)");
                monitorOfDeletion.notifyAll();
            }
            synchronized (monitorOfVerification) {
                monitorOfVerification.wait(500);
            }
            Thread.sleep(10);
            synchronized (monitorOfDeletion) {
                info(result, "VERIFICATION PROCESS - AFTER DELETION - " + getTableLines().size() + " line(s)");
                monitorOfDeletion.notifyAll();
            }
            synchronized (monitorOfVerification) {
                monitorOfVerification.wait(500);
            }
            Thread.sleep(10);
            synchronized (monitorOfDeletion) {
                info(result,
                        "VERIFICATION PROCESS - AFTER TRANSACTION - " + getTableLines().size() + " line(s)");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    List<Thread> threads = Arrays.asList(deletionVerifications, deletionProcess);
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join(2000);
    }
    return result;
}