Search in sources :

Example 1 with GridPlainRunnable

use of org.apache.ignite.internal.util.lang.GridPlainRunnable in project ignite by apache.

the class GridClosureProcessor method runLocal.

/**
     * @param c Closure to execute.
     * @param plc Whether to run on system or public pool.
     * @return Future.
     * @throws IgniteCheckedException Thrown in case of any errors.
     */
public IgniteInternalFuture<?> runLocal(@Nullable final Runnable c, byte plc) throws IgniteCheckedException {
    if (c == null)
        return new GridFinishedFuture();
    busyLock.readLock();
    try {
        // Inject only if needed.
        if (!(c instanceof GridPlainRunnable))
            ctx.resource().inject(ctx.deploy().getDeployment(c.getClass().getName()), c.getClass(), c);
        final ClassLoader ldr = Thread.currentThread().getContextClassLoader();
        final GridWorkerFuture fut = new GridWorkerFuture();
        GridWorker w = new GridWorker(ctx.igniteInstanceName(), "closure-proc-worker", log) {

            @Override
            protected void body() {
                try {
                    if (ldr != null)
                        U.wrapThreadLoader(ldr, c);
                    else
                        c.run();
                    fut.onDone();
                } catch (Throwable e) {
                    if (e instanceof Error)
                        U.error(log, "Closure execution failed with error.", e);
                    fut.onDone(U.cast(e));
                    if (e instanceof Error)
                        throw e;
                }
            }
        };
        fut.setWorker(w);
        try {
            pools.poolForPolicy(plc).execute(w);
        } catch (RejectedExecutionException e) {
            U.error(log, "Failed to execute worker due to execution rejection " + "(increase upper bound on executor service) [policy=" + plc + ']', e);
            w.run();
        }
        return fut;
    } finally {
        busyLock.readUnlock();
    }
}
Also used : GridWorkerFuture(org.apache.ignite.internal.util.worker.GridWorkerFuture) GridWorker(org.apache.ignite.internal.util.worker.GridWorker) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture)

Example 2 with GridPlainRunnable

use of org.apache.ignite.internal.util.lang.GridPlainRunnable in project ignite by apache.

the class GridNearOptimisticTxPrepareFutureAdapter method prepareOnTopology.

/**
     * @param remap Remap flag.
     * @param c Optional closure to run after map.
     */
protected final void prepareOnTopology(final boolean remap, @Nullable final Runnable c) {
    GridDhtTopologyFuture topFut = topologyReadLock();
    AffinityTopologyVersion topVer = null;
    try {
        if (topFut == null) {
            assert isDone();
            return;
        }
        if (topFut.isDone()) {
            topVer = topFut.topologyVersion();
            if (remap)
                tx.onRemap(topVer);
            else
                tx.topologyVersion(topVer);
            if (!remap)
                cctx.mvcc().addFuture(this);
        }
    } finally {
        topologyReadUnlock();
    }
    if (topVer != null) {
        IgniteCheckedException err = tx.txState().validateTopology(cctx, tx.writeMap().isEmpty(), topFut);
        if (err != null) {
            onDone(err);
            return;
        }
        prepare0(remap, false);
        if (c != null)
            c.run();
    } else {
        topFut.listen(new CI1<IgniteInternalFuture<AffinityTopologyVersion>>() {

            @Override
            public void apply(final IgniteInternalFuture<AffinityTopologyVersion> fut) {
                cctx.kernalContext().closure().runLocalSafe(new GridPlainRunnable() {

                    @Override
                    public void run() {
                        try {
                            fut.get();
                            prepareOnTopology(remap, c);
                        } catch (IgniteCheckedException e) {
                            onDone(e);
                        } finally {
                            cctx.txContextReset();
                        }
                    }
                });
            }
        });
    }
}
Also used : GridDhtTopologyFuture(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable)

Example 3 with GridPlainRunnable

use of org.apache.ignite.internal.util.lang.GridPlainRunnable in project ignite by apache.

the class GridDhtPreloader method request0.

/**
     * @param keys Keys to request.
     * @param topVer Topology version.
     * @return Future for request.
     */
@SuppressWarnings({ "unchecked", "RedundantCast" })
private GridDhtFuture<Object> request0(Collection<KeyCacheObject> keys, AffinityTopologyVersion topVer) {
    final GridDhtForceKeysFuture<?, ?> fut = new GridDhtForceKeysFuture<>(cctx, topVer, keys, this);
    IgniteInternalFuture<?> topReadyFut = cctx.affinity().affinityReadyFuturex(topVer);
    if (startFut.isDone() && topReadyFut == null)
        fut.init();
    else {
        if (topReadyFut == null)
            startFut.listen(new CI1<IgniteInternalFuture<?>>() {

                @Override
                public void apply(IgniteInternalFuture<?> syncFut) {
                    cctx.kernalContext().closure().runLocalSafe(new GridPlainRunnable() {

                        @Override
                        public void run() {
                            fut.init();
                        }
                    });
                }
            });
        else {
            GridCompoundFuture<Object, Object> compound = new GridCompoundFuture<>();
            compound.add((IgniteInternalFuture<Object>) startFut);
            compound.add((IgniteInternalFuture<Object>) topReadyFut);
            compound.markInitialized();
            compound.listen(new CI1<IgniteInternalFuture<?>>() {

                @Override
                public void apply(IgniteInternalFuture<?> syncFut) {
                    fut.init();
                }
            });
        }
    }
    return (GridDhtFuture) fut;
}
Also used : GridDhtFuture(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtFuture) CI1(org.apache.ignite.internal.util.typedef.CI1) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture)

Example 4 with GridPlainRunnable

use of org.apache.ignite.internal.util.lang.GridPlainRunnable in project ignite by apache.

the class GridDhtCacheEntry method addReader.

/**
     * @param nodeId Reader to add.
     * @param msgId Message ID.
     * @param topVer Topology version.
     * @return Future for all relevant transactions that were active at the time of adding reader,
     *      or {@code null} if reader was added
     * @throws GridCacheEntryRemovedException If entry was removed.
     */
@SuppressWarnings("unchecked")
@Nullable
public IgniteInternalFuture<Boolean> addReader(UUID nodeId, long msgId, AffinityTopologyVersion topVer) throws GridCacheEntryRemovedException {
    // Don't add local node as reader.
    if (cctx.nodeId().equals(nodeId))
        return null;
    ClusterNode node = cctx.discovery().node(nodeId);
    if (node == null) {
        if (log.isDebugEnabled())
            log.debug("Ignoring near reader because node left the grid: " + nodeId);
        return null;
    }
    // If remote node has no near cache, don't add it.
    if (!cctx.discovery().cacheNearNode(node, cacheName())) {
        if (log.isDebugEnabled())
            log.debug("Ignoring near reader because near cache is disabled: " + nodeId);
        return null;
    }
    // If remote node is (primary?) or back up, don't add it as a reader.
    if (cctx.affinity().partitionBelongs(node, partition(), topVer)) {
        if (log.isDebugEnabled())
            log.debug("Ignoring near reader because remote node is affinity node [locNodeId=" + cctx.localNodeId() + ", rmtNodeId=" + nodeId + ", key=" + key + ']');
        return null;
    }
    boolean ret = false;
    GridCacheMultiTxFuture txFut = null;
    Collection<GridCacheMvccCandidate> cands = null;
    ReaderId reader;
    synchronized (this) {
        checkObsolete();
        reader = readerId(nodeId);
        if (reader == null) {
            reader = new ReaderId(nodeId, msgId);
            ReaderId[] rdrs = Arrays.copyOf(this.rdrs, this.rdrs.length + 1);
            rdrs[rdrs.length - 1] = reader;
            // Seal.
            this.rdrs = rdrs;
            // No transactions in ATOMIC cache.
            if (!cctx.atomic()) {
                txFut = reader.getOrCreateTxFuture(cctx);
                cands = localCandidates();
                ret = true;
            }
        } else {
            txFut = reader.txFuture();
            long id = reader.messageId();
            if (id < msgId)
                reader.messageId(msgId);
        }
    }
    if (ret) {
        assert txFut != null;
        if (!F.isEmpty(cands)) {
            for (GridCacheMvccCandidate c : cands) {
                IgniteInternalTx tx = cctx.tm().tx(c.version());
                if (tx != null && tx.local())
                    txFut.addTx(tx);
            }
        }
        txFut.init();
        if (!txFut.isDone()) {
            final ReaderId reader0 = reader;
            txFut.listen(new CI1<IgniteInternalFuture<?>>() {

                @Override
                public void apply(IgniteInternalFuture<?> f) {
                    cctx.kernalContext().closure().runLocalSafe(new GridPlainRunnable() {

                        @Override
                        public void run() {
                            synchronized (this) {
                                // Release memory.
                                reader0.resetTxFuture();
                            }
                        }
                    });
                }
            });
        } else {
            synchronized (this) {
                // Release memory.
                reader.resetTxFuture();
            }
            txFut = null;
        }
    }
    return txFut;
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable) GridCacheMultiTxFuture(org.apache.ignite.internal.processors.cache.GridCacheMultiTxFuture) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) GridCacheMvccCandidate(org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with GridPlainRunnable

use of org.apache.ignite.internal.util.lang.GridPlainRunnable in project ignite by apache.

the class IgniteH2Indexing method send.

/**
     * @param topic Topic.
     * @param topicOrd Topic ordinal for {@link GridTopic}.
     * @param nodes Nodes.
     * @param msg Message.
     * @param specialize Optional closure to specialize message for each node.
     * @param locNodeHnd Handler for local node.
     * @param plc Policy identifying the executor service which will process message.
     * @param runLocParallel Run local handler in parallel thread.
     * @return {@code true} If all messages sent successfully.
     */
public boolean send(Object topic, int topicOrd, Collection<ClusterNode> nodes, Message msg, @Nullable IgniteBiClosure<ClusterNode, Message, Message> specialize, @Nullable final IgniteInClosure2X<ClusterNode, Message> locNodeHnd, byte plc, boolean runLocParallel) {
    boolean ok = true;
    if (specialize == null && msg instanceof GridCacheQueryMarshallable)
        ((GridCacheQueryMarshallable) msg).marshall(marshaller);
    ClusterNode locNode = null;
    for (ClusterNode node : nodes) {
        if (node.isLocal()) {
            if (locNode != null)
                throw new IllegalStateException();
            locNode = node;
            continue;
        }
        try {
            if (specialize != null) {
                msg = specialize.apply(node, msg);
                if (msg instanceof GridCacheQueryMarshallable)
                    ((GridCacheQueryMarshallable) msg).marshall(marshaller);
            }
            ctx.io().sendGeneric(node, topic, topicOrd, msg, plc);
        } catch (IgniteCheckedException e) {
            ok = false;
            U.warn(log, "Failed to send message [node=" + node + ", msg=" + msg + ", errMsg=" + e.getMessage() + "]");
        }
    }
    // Local node goes the last to allow parallel execution.
    if (locNode != null) {
        assert locNodeHnd != null;
        if (specialize != null)
            msg = specialize.apply(locNode, msg);
        if (runLocParallel) {
            final ClusterNode finalLocNode = locNode;
            final Message finalMsg = msg;
            try {
                // We prefer runLocal to runLocalSafe, because the latter can produce deadlock here.
                ctx.closure().runLocal(new GridPlainRunnable() {

                    @Override
                    public void run() {
                        if (!busyLock.enterBusy())
                            return;
                        try {
                            locNodeHnd.apply(finalLocNode, finalMsg);
                        } finally {
                            busyLock.leaveBusy();
                        }
                    }
                }, plc).listen(logger);
            } catch (IgniteCheckedException e) {
                ok = false;
                U.error(log, "Failed to execute query locally.", e);
            }
        } else
            locNodeHnd.apply(locNode, msg);
    }
    return ok;
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Message(org.apache.ignite.plugin.extensions.communication.Message) GridCacheQueryMarshallable(org.apache.ignite.internal.processors.cache.query.GridCacheQueryMarshallable) GridPlainRunnable(org.apache.ignite.internal.util.lang.GridPlainRunnable)

Aggregations

GridPlainRunnable (org.apache.ignite.internal.util.lang.GridPlainRunnable)6 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)3 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)2 ClusterNode (org.apache.ignite.cluster.ClusterNode)2 CountDownLatch (java.util.concurrent.CountDownLatch)1 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)1 IgniteInterruptedException (org.apache.ignite.IgniteInterruptedException)1 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)1 GridCacheMultiTxFuture (org.apache.ignite.internal.processors.cache.GridCacheMultiTxFuture)1 GridCacheMvccCandidate (org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate)1 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)1 GridDhtFuture (org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtFuture)1 GridDhtTopologyFuture (org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture)1 GridCacheQueryMarshallable (org.apache.ignite.internal.processors.cache.query.GridCacheQueryMarshallable)1 IgniteInternalTx (org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx)1 GridCompoundFuture (org.apache.ignite.internal.util.future.GridCompoundFuture)1 GridFinishedFuture (org.apache.ignite.internal.util.future.GridFinishedFuture)1 CI1 (org.apache.ignite.internal.util.typedef.CI1)1 GridWorker (org.apache.ignite.internal.util.worker.GridWorker)1 GridWorkerFuture (org.apache.ignite.internal.util.worker.GridWorkerFuture)1