Search in sources :

Example 31 with Condition

use of java.util.concurrent.locks.Condition in project geode by apache.

the class Producer method run.

public void run() {
    Object key = null;
    final ReentrantLock dr = RLJBarJUnitTest.DeathRow;
    final ReentrantLock bar = RLJBarJUnitTest.bar;
    final ReentrantLock end = RLJBarJUnitTest.End;
    final Condition endCondition = RLJBarJUnitTest.EndCondition;
    if (RLJBarJUnitTest.OneKey)
        // per-thread v. per iteration
        key = new Integer(0);
    try {
        bar.lock();
        try {
            ++RLJBarJUnitTest.nUp;
            if (RLJBarJUnitTest.nUp == RLJBarJUnitTest.nThreads) {
                if (RLJBarJUnitTest.quiesce != 0) {
                    RLJBarJUnitTest.barCondition.await(RLJBarJUnitTest.quiesce * 1000000, TimeUnit.NANOSECONDS);
                }
                RLJBarJUnitTest.epoch = System.currentTimeMillis();
                RLJBarJUnitTest.barCondition.signalAll();
            // System.out.print ("Consensus ") ;
            }
            if (RLJBarJUnitTest.UseBar) {
                while (RLJBarJUnitTest.nUp != RLJBarJUnitTest.nThreads) {
                    RLJBarJUnitTest.barCondition.await();
                }
            }
        } finally {
            bar.unlock();
        }
    } catch (Exception ex) {
        System.out.println("Exception in barrier: " + ex);
    }
    // HashTable.get() is highly contended (serial).
    for (int loop = 1; loop < 100000; loop++) {
        if (!RLJBarJUnitTest.OneKey)
            key = new Integer(0);
        buddiesOnline.get(key);
    }
    // Mutator epilog:
    // The following code determines if the test will/wont include (measure)
    // thread death time.
    end.lock();
    try {
        ++RLJBarJUnitTest.nDead;
        if (RLJBarJUnitTest.nDead == RLJBarJUnitTest.nUp) {
            // System.out.print((System.currentTimeMillis()-RLJBar.epoch) + " ms") ;
            endCondition.signalAll();
        }
    } finally {
        end.unlock();
    }
    dr.lock();
    dr.unlock();
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition)

Example 32 with Condition

use of java.util.concurrent.locks.Condition in project ignite by apache.

the class GridJobProcessor method requestJobSiblings.

/**
     * @param ses Session.
     * @return Siblings.
     * @throws IgniteCheckedException If failed.
     */
public Collection<ComputeJobSibling> requestJobSiblings(final ComputeTaskSession ses) throws IgniteCheckedException {
    assert ses != null;
    final UUID taskNodeId = ses.getTaskNodeId();
    ClusterNode taskNode = ctx.discovery().node(taskNodeId);
    if (taskNode == null)
        throw new IgniteCheckedException("Node that originated task execution has left grid: " + taskNodeId);
    // Tuple: error message-response.
    final IgniteBiTuple<String, GridJobSiblingsResponse> t = new IgniteBiTuple<>();
    final Lock lock = new ReentrantLock();
    final Condition cond = lock.newCondition();
    GridMessageListener msgLsnr = new GridMessageListener() {

        @Override
        public void onMessage(UUID nodeId, Object msg) {
            String err = null;
            GridJobSiblingsResponse res = null;
            if (!(msg instanceof GridJobSiblingsResponse))
                err = "Received unexpected message: " + msg;
            else if (!nodeId.equals(taskNodeId))
                err = "Received job siblings response from unexpected node [taskNodeId=" + taskNodeId + ", nodeId=" + nodeId + ']';
            else {
                // Sender and message type are fine.
                res = (GridJobSiblingsResponse) msg;
                if (res.jobSiblings() == null) {
                    try {
                        res.unmarshalSiblings(marsh);
                    } catch (IgniteCheckedException e) {
                        U.error(log, "Failed to unmarshal job siblings.", e);
                        err = e.getMessage();
                    }
                }
            }
            lock.lock();
            try {
                if (t.isEmpty()) {
                    t.set(err, res);
                    cond.signalAll();
                }
            } finally {
                lock.unlock();
            }
        }
    };
    GridLocalEventListener discoLsnr = new GridLocalEventListener() {

        @Override
        public void onEvent(Event evt) {
            assert evt instanceof DiscoveryEvent && (evt.type() == EVT_NODE_FAILED || evt.type() == EVT_NODE_LEFT) : "Unexpected event: " + evt;
            DiscoveryEvent discoEvt = (DiscoveryEvent) evt;
            if (taskNodeId.equals(discoEvt.eventNode().id())) {
                lock.lock();
                try {
                    if (t.isEmpty()) {
                        t.set("Node that originated task execution has left grid: " + taskNodeId, null);
                        cond.signalAll();
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    };
    boolean loc = ctx.localNodeId().equals(taskNodeId);
    // 1. Create unique topic name.
    Object topic = TOPIC_JOB_SIBLINGS.topic(ses.getId(), topicIdGen.getAndIncrement());
    try {
        // 2. Register listener.
        ctx.io().addMessageListener(topic, msgLsnr);
        // 3. Send message.
        ctx.io().sendToGridTopic(taskNode, TOPIC_JOB_SIBLINGS, new GridJobSiblingsRequest(ses.getId(), loc ? topic : null, loc ? null : U.marshal(marsh, topic)), SYSTEM_POOL);
        // 4. Listen to discovery events.
        ctx.event().addLocalEventListener(discoLsnr, EVT_NODE_FAILED, EVT_NODE_LEFT);
        // 5. Check whether node has left before disco listener has been installed.
        taskNode = ctx.discovery().node(taskNodeId);
        if (taskNode == null)
            throw new IgniteCheckedException("Node that originated task execution has left grid: " + taskNodeId);
        // 6. Wait for result.
        lock.lock();
        try {
            long netTimeout = ctx.config().getNetworkTimeout();
            if (t.isEmpty())
                cond.await(netTimeout, MILLISECONDS);
            if (t.isEmpty())
                throw new IgniteCheckedException("Timed out waiting for job siblings (consider increasing" + "'networkTimeout' configuration property) [ses=" + ses + ", netTimeout=" + netTimeout + ']');
            // Error is set?
            if (t.get1() != null)
                throw new IgniteCheckedException(t.get1());
            else
                // Return result
                return t.get2().jobSiblings();
        } catch (InterruptedException e) {
            throw new IgniteCheckedException("Interrupted while waiting for job siblings response: " + ses, e);
        } finally {
            lock.unlock();
        }
    } finally {
        ctx.io().removeMessageListener(topic, msgLsnr);
        ctx.event().removeLocalEventListener(discoLsnr);
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) GridLocalEventListener(org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) GridJobSiblingsResponse(org.apache.ignite.internal.GridJobSiblingsResponse) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) GridSpinReadWriteLock(org.apache.ignite.internal.util.GridSpinReadWriteLock) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) GridJobSiblingsRequest(org.apache.ignite.internal.GridJobSiblingsRequest) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) JobEvent(org.apache.ignite.events.JobEvent) TaskEvent(org.apache.ignite.events.TaskEvent) Event(org.apache.ignite.events.Event) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) UUID(java.util.UUID)

Example 33 with Condition

use of java.util.concurrent.locks.Condition in project ignite by apache.

the class OffheapReadWriteLock method waitAcquireWriteLock.

/**
     * Acquires write lock in waiting loop.
     *
     * @param lock Lock address.
     * @param lockIdx Lock index.
     * @param tag Validation tag.
     * @return {@code True} if lock was acquired, {@code false} if tag validation failed.
     */
private boolean waitAcquireWriteLock(long lock, int lockIdx, int tag) {
    ReentrantLock lockObj = locks[lockIdx];
    Condition waitCond = writeConditions[lockIdx];
    assert lockObj.isHeldByCurrentThread();
    boolean interrupted = false;
    try {
        while (true) {
            try {
                long state = GridUnsafe.getLongVolatile(null, lock);
                if (!checkTag(state, tag)) {
                    // We cannot lock with this tag, release waiter.
                    long updated = updateState(state, 0, 0, -1);
                    if (GridUnsafe.compareAndSwapLong(null, lock, state, updated)) {
                        int writeWaitCnt = writersWaitCount(updated);
                        int readWaitCnt = readersWaitCount(updated);
                        signalNextWaiter(writeWaitCnt, readWaitCnt, lockIdx);
                        return false;
                    }
                } else if (canWriteLock(state)) {
                    long updated = updateState(state, -1, 0, -1);
                    if (GridUnsafe.compareAndSwapLong(null, lock, state, updated))
                        return true;
                } else
                    waitCond.await();
            } catch (InterruptedException ignore) {
                interrupted = true;
            }
        }
    } finally {
        if (interrupted)
            Thread.currentThread().interrupt();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition)

Example 34 with Condition

use of java.util.concurrent.locks.Condition in project ignite by apache.

the class OffheapReadWriteLock method signalNextWaiter.

/**
     * @param writeWaitCnt Writers wait count.
     * @param readWaitCnt Readers wait count.
     * @param idx Lock index.
     */
private void signalNextWaiter(int writeWaitCnt, int readWaitCnt, int idx) {
    if (writeWaitCnt == 0) {
        Condition readCondition = readConditions[idx];
        readCondition.signalAll();
    } else if (readWaitCnt == 0) {
        Condition writeCond = writeConditions[idx];
        writeCond.signalAll();
    } else {
        // We have both writers and readers.
        if (USE_RANDOM_RW_POLICY) {
            boolean write = (balancers[idx].incrementAndGet() & 0x1) == 0;
            Condition cond = (write ? writeConditions : readConditions)[idx];
            cond.signalAll();
        } else {
            Condition cond = writeConditions[idx];
            cond.signalAll();
        }
    }
}
Also used : Condition(java.util.concurrent.locks.Condition)

Aggregations

Condition (java.util.concurrent.locks.Condition)34 ReentrantLock (java.util.concurrent.locks.ReentrantLock)20 Lock (java.util.concurrent.locks.Lock)14 Test (org.junit.Test)9 HttpResponse (org.apache.http.HttpResponse)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 ByteBuffer (java.nio.ByteBuffer)3 User (com.lonepulse.robozombie.model.User)2 InvocationException (com.lonepulse.robozombie.proxy.InvocationException)2 UUID (java.util.UUID)2 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)2 ClusterNode (org.apache.ignite.cluster.ClusterNode)2 DiscoveryEvent (org.apache.ignite.events.DiscoveryEvent)2 Event (org.apache.ignite.events.Event)2 GridMessageListener (org.apache.ignite.internal.managers.communication.GridMessageListener)2 GridLocalEventListener (org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener)2 IgniteBiTuple (org.apache.ignite.lang.IgniteBiTuple)2 Test (org.testng.annotations.Test)2 TaskMessage (backtype.storm.messaging.TaskMessage)1 AbstractCacheListener (co.paralleluniverse.galaxy.AbstractCacheListener)1