Example usage for java.lang Thread holdsLock

List of usage examples for java.lang Thread holdsLock

Introduction

In this page you can find the example usage for java.lang Thread holdsLock.

Prototype

public static native boolean holdsLock(Object obj);

Source Link

Document

Returns true if and only if the current thread holds the monitor lock on the specified object.

Usage

From source file:org.apache.ignite.internal.managers.deployment.GridDeploymentClassLoader.java

/** {@inheritDoc} */
@Nullable/*from w w  w.  j  a  v a  2  s  .  c om*/
@Override
public InputStream getResourceAsStream(String name) {
    assert !Thread.holdsLock(mux);

    if (byteMap != null && name.endsWith(".class")) {
        byte[] bytes = byteMap.get(name);

        if (bytes != null) {
            if (log.isDebugEnabled())
                log.debug("Got class definition from byte code cache: " + name);

            return new ByteArrayInputStream(bytes);
        }
    }

    InputStream in = ClassLoader.getSystemResourceAsStream(name);

    if (in == null)
        in = super.getResourceAsStream(name);

    // Most probably, this is initiated by GridUtils.getUserVersion().
    // No point to send request.
    if ("META-INF/services/org.apache.commons.logging.LogFactory".equalsIgnoreCase(name)) {
        if (log.isDebugEnabled())
            log.debug(
                    "Denied sending remote request for META-INF/services/org.apache.commons.logging.LogFactory.");

        return null;
    }

    if (in == null)
        in = sendResourceRequest(name);

    return in;
}

From source file:org.apache.ignite.internal.managers.deployment.GridDeploymentClassLoader.java

/**
 * Sends resource request to all remote nodes associated with this class loader.
 *
 * @param name Resource name./*from   w w w  .j a va2  s. c om*/
 * @return InputStream for resource or {@code null} if resource could not be found.
 */
@Nullable
private InputStream sendResourceRequest(String name) {
    assert !Thread.holdsLock(mux);

    long endTime = computeEndTime(p2pTimeout);

    Collection<UUID> nodeListCp;
    Map<UUID, IgniteUuid> nodeLdrMapCp;

    synchronized (mux) {
        // Skip requests for the previously missed classes.
        if (missedRsrcs != null && missedRsrcs.contains(name))
            return null;

        // If single-node mode, then node cannot change and we simply reuse list and map.
        // Otherwise, make copies that can be used outside synchronization.
        nodeListCp = singleNode ? nodeList : new LinkedList<>(nodeList);
        nodeLdrMapCp = singleNode ? nodeLdrMap : new HashMap<>(nodeLdrMap);
    }

    for (UUID nodeId : nodeListCp) {
        if (nodeId.equals(ctx.discovery().localNode().id()))
            // Skip local node as it is already used as parent class loader.
            continue;

        IgniteUuid ldrId = nodeLdrMapCp.get(nodeId);

        ClusterNode node = ctx.discovery().node(nodeId);

        if (node == null) {
            if (log.isDebugEnabled())
                log.debug("Found inactive node in class loader (will skip): " + nodeId);

            continue;
        }

        try {
            // Request is sent with timeout that is why we can use synchronization here.
            GridDeploymentResponse res = comm.sendResourceRequest(name, ldrId, node, endTime);

            if (res == null) {
                U.warn(log, "Failed to get resource from node (is node alive?) [nodeId=" + node.id()
                        + ", clsLdrId=" + ldrId + ", resName=" + name + ", parentClsLdr=" + getParent() + ']');
            } else if (!res.success()) {
                synchronized (mux) {
                    // Cache unsuccessfully loaded resource.
                    if (missedRsrcs != null)
                        missedRsrcs.add(name);
                }

                // Some frameworks like Spring often ask for the resources
                // just in case - none will happen if there are no such
                // resources. So we print out INFO level message.
                if (!quiet) {
                    if (log.isInfoEnabled())
                        log.info("Failed to get resource from node [nodeId=" + node.id() + ", clsLdrId=" + ldrId
                                + ", resName=" + name + ", parentClsLdr=" + getParent() + ", msg="
                                + res.errorMessage() + ']');
                } else if (log.isDebugEnabled())
                    log.debug("Failed to get resource from node [nodeId=" + node.id() + ", clsLdrId=" + ldrId
                            + ", resName=" + name + ", parentClsLdr=" + getParent() + ", msg="
                            + res.errorMessage() + ']');

                // Do not ask other nodes in case of shared mode all of them should have the resource.
                return null;
            } else {
                return new ByteArrayInputStream(res.byteSource().internalArray(), 0, res.byteSource().size());
            }
        } catch (IgniteCheckedException e) {
            // This thread should be interrupted again in communication if it
            // got interrupted. So we assume that thread can be interrupted
            // by processing cancellation request.
            if (Thread.currentThread().isInterrupted()) {
                if (!quiet)
                    U.error(log, "Failed to get resource probably due to task/job cancellation: " + name, e);
                else if (log.isDebugEnabled())
                    log.debug("Failed to get resource probably due to task/job cancellation: " + name);
            } else {
                if (!quiet)
                    U.warn(log,
                            "Failed to get resource from node (is node alive?) [nodeId=" + node.id()
                                    + ", clsLdrId=" + ldrId + ", resName=" + name + ", parentClsLdr="
                                    + getParent() + ", err=" + e + ']');
                else if (log.isDebugEnabled())
                    log.debug("Failed to get resource from node (is node alive?) [nodeId=" + node.id()
                            + ", clsLdrId=" + ldrId + ", resName=" + name + ", parentClsLdr=" + getParent()
                            + ", err=" + e + ']');
            }
        }
    }

    return null;
}

From source file:org.apache.ignite.internal.processors.hadoop.impl.igfs.HadoopIgfsInProc.java

/**
 * Creates instance of the HadoopIgfsInProcWithIgniteRefsCount by IGFS name.
 *
 * @param ignite Ignite instance./*from  w  w  w  .  j  av  a  2  s .c  o  m*/
 * @param igfsName Target IGFS name.
 * @param log Log.
 * @param userName User name.
 * @return HadoopIgfsInProcWithIgniteRefsCount instance. {@code null} if the IGFS not found
 *      in the specified ignite instance.
 */
private static HadoopIgfsInProc create0(Ignite ignite, String igfsName, Log log, String userName) {
    assert Thread.holdsLock(REF_CTR_MUX);
    assert ignite != null;

    if (Ignition.state(ignite.name()) == STARTED) {
        try {
            for (IgniteFileSystem fs : ignite.fileSystems()) {
                if (F.eq(fs.name(), igfsName)) {
                    Integer ctr = REF_CTRS.get(ignite.name());

                    if (ctr != null)
                        REF_CTRS.put(ignite.name(), ctr + 1);

                    return new HadoopIgfsInProc((IgfsEx) fs, log, userName);
                }
            }
        } catch (IllegalStateException ignore) {
            // May happen if the grid state has changed:
        }
    }

    return null;
}

From source file:org.apache.lucene.index.IndexWriter.java

boolean holdsFullFlushLock() {
    return Thread.holdsLock(fullFlushLock);
}

From source file:org.apache.solr.cloud.ZkController.java

private Set<Runnable> getConfDirListeners(final String confDir) {
    assert Thread.holdsLock(confDirectoryListeners) : "confDirListeners lock not held by thread";
    Set<Runnable> confDirListeners = confDirectoryListeners.get(confDir);
    if (confDirListeners == null) {
        log.debug("watch zkdir {}", confDir);
        confDirListeners = new HashSet<>();
        confDirectoryListeners.put(confDir, confDirListeners);
        setConfWatcher(confDir, new WatcherImpl(confDir), null);
    }/*from w  w w . j a v a 2s.  com*/
    return confDirListeners;
}

From source file:org.dragonet.plugin.MixedPluginManager.java

/**
 * Calls an event with the given details.
 * <p>/* w w  w .  jav  a 2s  .com*/
 * This method only synchronizes when the event is not asynchronous.
 *
 * @param event Event details
 */
public void callEvent(Event event) {
    if (event.isAsynchronous()) {
        if (Thread.holdsLock(this)) {
            throw new IllegalStateException(event.getEventName()
                    + " cannot be triggered asynchronously from inside synchronized code.");
        }
        if (server.isPrimaryThread()) {
            throw new IllegalStateException(
                    event.getEventName() + " cannot be triggered asynchronously from primary server thread.");
        }
        fireEvent(event);
    } else {
        synchronized (this) {
            fireEvent(event);
        }
    }
}

From source file:org.gridgain.grid.kernal.managers.deployment.GridDeploymentClassLoader.java

/** {@inheritDoc} */
@Override/*from  w w  w.  ja  v a  2s. c  o  m*/
public Class<?> loadClass(String name) throws ClassNotFoundException {
    assert !Thread.holdsLock(mux);

    // Check if we have package name on list of P2P loaded.
    // GridComputeJob must be always loaded locally to avoid
    // any possible class casting issues.
    Class<?> cls = null;

    try {
        if (!"org.gridgain.grid.GridComputeJob".equals(name)) {
            if (isLocallyExcluded(name))
                // P2P loaded class.
                cls = p2pLoadClass(name, true);
        }

        if (cls == null)
            cls = loadClass(name, true);
    } catch (ClassNotFoundException e) {
        throw e;
    }
    // Catch Throwable to secure against any errors resulted from
    // corrupted class definitions or other user errors.
    catch (Throwable e) {
        throw new ClassNotFoundException("Failed to load class due to unexpected error: " + name, e);
    }

    return cls;
}

From source file:org.gridgain.grid.kernal.managers.deployment.GridDeploymentClassLoader.java

/**
 * Sends class-loading request to all nodes associated with this class loader.
 *
 * @param name Class name./*from w ww  .  j  a  v  a  2 s  .  co  m*/
 * @param path Class path.
 * @return Class byte source.
 * @throws ClassNotFoundException If class was not found.
 */
private GridByteArrayList sendClassRequest(String name, String path) throws ClassNotFoundException {
    assert !Thread.holdsLock(mux);

    long endTime = computeEndTime(p2pTimeout);

    Collection<UUID> nodeListCp;
    Map<UUID, GridUuid> nodeLdrMapCp;

    synchronized (mux) {
        // Skip requests for the previously missed classes.
        if (missedRsrcs != null && missedRsrcs.contains(path))
            throw new ClassNotFoundException("Failed to peer load class [class=" + name + ", nodeClsLdrIds="
                    + nodeLdrMap + ", parentClsLoader=" + getParent() + ']');

        // If single-node mode, then node cannot change and we simply reuse list and map.
        // Otherwise, make copies that can be used outside synchronization.
        nodeListCp = singleNode ? nodeList : new LinkedList<>(nodeList);
        nodeLdrMapCp = singleNode ? nodeLdrMap : new HashMap<>(nodeLdrMap);
    }

    GridException err = null;

    for (UUID nodeId : nodeListCp) {
        if (nodeId.equals(ctx.discovery().localNode().id()))
            // Skip local node as it is already used as parent class loader.
            continue;

        GridUuid ldrId = nodeLdrMapCp.get(nodeId);

        GridNode node = ctx.discovery().node(nodeId);

        if (node == null) {
            if (log.isDebugEnabled())
                log.debug("Found inactive node in class loader (will skip): " + nodeId);

            continue;
        }

        try {
            GridDeploymentResponse res = comm.sendResourceRequest(path, ldrId, node, endTime);

            if (res == null) {
                String msg = "Failed to send class-loading request to node (is node alive?) [node=" + node.id()
                        + ", clsName=" + name + ", clsPath=" + path + ", clsLdrId=" + ldrId + ", parentClsLdr="
                        + getParent() + ']';

                if (!quiet)
                    U.warn(log, msg);
                else if (log.isDebugEnabled())
                    log.debug(msg);

                err = new GridException(msg);

                continue;
            }

            if (res.success())
                return res.byteSource();

            // In case of shared resources/classes all nodes should have it.
            if (log.isDebugEnabled())
                log.debug("Failed to find class on remote node [class=" + name + ", nodeId=" + node.id()
                        + ", clsLdrId=" + ldrId + ", reason=" + res.errorMessage() + ']');

            synchronized (mux) {
                if (missedRsrcs != null)
                    missedRsrcs.add(path);
            }

            throw new ClassNotFoundException(
                    "Failed to peer load class [class=" + name + ", nodeClsLdrs=" + nodeLdrMapCp
                            + ", parentClsLoader=" + getParent() + ", reason=" + res.errorMessage() + ']');
        } catch (GridException e) {
            // This thread should be interrupted again in communication if it
            // got interrupted. So we assume that thread can be interrupted
            // by processing cancellation request.
            if (Thread.currentThread().isInterrupted()) {
                if (!quiet)
                    U.error(log, "Failed to find class probably due to task/job cancellation: " + name, e);
                else if (log.isDebugEnabled())
                    log.debug("Failed to find class probably due to task/job cancellation [name=" + name
                            + ", err=" + e + ']');
            } else {
                if (!quiet)
                    U.warn(log,
                            "Failed to send class-loading request to node (is node alive?) [node=" + node.id()
                                    + ", clsName=" + name + ", clsPath=" + path + ", clsLdrId=" + ldrId
                                    + ", parentClsLdr=" + getParent() + ", err=" + e + ']');
                else if (log.isDebugEnabled())
                    log.debug("Failed to send class-loading request to node (is node alive?) [node=" + node.id()
                            + ", clsName=" + name + ", clsPath=" + path + ", clsLdrId=" + ldrId
                            + ", parentClsLdr=" + getParent() + ", err=" + e + ']');

                err = e;
            }
        }
    }

    throw new ClassNotFoundException("Failed to peer load class [class=" + name + ", nodeClsLdrs="
            + nodeLdrMapCp + ", parentClsLoader=" + getParent() + ']', err);
}

From source file:org.gridgain.grid.kernal.managers.deployment.GridDeploymentClassLoader.java

/**
 * Sends resource request to all remote nodes associated with this class loader.
 *
 * @param name Resource name./*from ww w  .  ja va 2s . co m*/
 * @return InputStream for resource or {@code null} if resource could not be found.
 */
@Nullable
private InputStream sendResourceRequest(String name) {
    assert !Thread.holdsLock(mux);

    long endTime = computeEndTime(p2pTimeout);

    Collection<UUID> nodeListCp;
    Map<UUID, GridUuid> nodeLdrMapCp;

    synchronized (mux) {
        // Skip requests for the previously missed classes.
        if (missedRsrcs != null && missedRsrcs.contains(name))
            return null;

        // If single-node mode, then node cannot change and we simply reuse list and map.
        // Otherwise, make copies that can be used outside synchronization.
        nodeListCp = singleNode ? nodeList : new LinkedList<>(nodeList);
        nodeLdrMapCp = singleNode ? nodeLdrMap : new HashMap<>(nodeLdrMap);
    }

    for (UUID nodeId : nodeListCp) {
        if (nodeId.equals(ctx.discovery().localNode().id()))
            // Skip local node as it is already used as parent class loader.
            continue;

        GridUuid ldrId = nodeLdrMapCp.get(nodeId);

        GridNode node = ctx.discovery().node(nodeId);

        if (node == null) {
            if (log.isDebugEnabled())
                log.debug("Found inactive node in class loader (will skip): " + nodeId);

            continue;
        }

        try {
            // Request is sent with timeout that is why we can use synchronization here.
            GridDeploymentResponse res = comm.sendResourceRequest(name, ldrId, node, endTime);

            if (res == null) {
                U.warn(log, "Failed to get resource from node (is node alive?) [nodeId=" + node.id()
                        + ", clsLdrId=" + ldrId + ", resName=" + name + ", parentClsLdr=" + getParent() + ']');
            } else if (!res.success()) {
                synchronized (mux) {
                    // Cache unsuccessfully loaded resource.
                    if (missedRsrcs != null)
                        missedRsrcs.add(name);
                }

                // Some frameworks like Spring often ask for the resources
                // just in case - none will happen if there are no such
                // resources. So we print out INFO level message.
                if (!quiet) {
                    if (log.isInfoEnabled())
                        log.info("Failed to get resource from node [nodeId=" + node.id() + ", clsLdrId=" + ldrId
                                + ", resName=" + name + ", parentClsLdr=" + getParent() + ", msg="
                                + res.errorMessage() + ']');
                } else if (log.isDebugEnabled())
                    log.debug("Failed to get resource from node [nodeId=" + node.id() + ", clsLdrId=" + ldrId
                            + ", resName=" + name + ", parentClsLdr=" + getParent() + ", msg="
                            + res.errorMessage() + ']');

                // Do not ask other nodes in case of shared mode all of them should have the resource.
                return null;
            } else {
                return new ByteArrayInputStream(res.byteSource().internalArray(), 0, res.byteSource().size());
            }
        } catch (GridException e) {
            // This thread should be interrupted again in communication if it
            // got interrupted. So we assume that thread can be interrupted
            // by processing cancellation request.
            if (Thread.currentThread().isInterrupted()) {
                if (!quiet)
                    U.error(log, "Failed to get resource probably due to task/job cancellation: " + name, e);
                else if (log.isDebugEnabled())
                    log.debug("Failed to get resource probably due to task/job cancellation: " + name);
            } else {
                if (!quiet)
                    U.warn(log,
                            "Failed to get resource from node (is node alive?) [nodeId=" + node.id()
                                    + ", clsLdrId=" + ldrId + ", resName=" + name + ", parentClsLdr="
                                    + getParent() + ", err=" + e + ']');
                else if (log.isDebugEnabled())
                    log.debug("Failed to get resource from node (is node alive?) [nodeId=" + node.id()
                            + ", clsLdrId=" + ldrId + ", resName=" + name + ", parentClsLdr=" + getParent()
                            + ", err=" + e + ']');
            }
        }
    }

    return null;
}

From source file:org.openconcerto.sql.model.graph.DatabaseGraph.java

/**
 * Construit la carte des tables//w ww .  jav  a  2  s  . c  o  m
 * 
 * @param toRefreshSpec the roots and tables to refresh.
 * @return roots and tables loaded from file.
 * @throws SQLException if an error occurs.
 */
private synchronized Map<String, Set<String>> mapTables(final ToRefreshSpec toRefreshSpec) throws SQLException {
    assert Thread.holdsLock(this.base.getTreeMutex()) : "Cannot graph a changing object";
    Map<String, Set<String>> res = new TablesMap();

    final Set<SQLTable> currentTables = this.getAllTables();
    final ToRefreshActual toRefresh = toRefreshSpec.getActual(this.base, currentTables);
    // clear graph and add tables (vertices)
    {
        final Set<SQLTable> newTablesInScope = toRefresh.getNewTablesInScope();
        final Set<SQLTable> oldTablesInScope = toRefresh.getOldTablesInScope();
        // refresh all ?
        final boolean clearGraph = oldTablesInScope.equals(currentTables);

        // clear cache
        synchronized (this) {
            if (clearGraph) {
                this.foreignLink.clear();
                this.foreignLinks.clear();
            } else {
                for (final Iterator<Entry<List<SQLField>, Link>> iter = this.foreignLink.entrySet()
                        .iterator(); iter.hasNext();) {
                    final Entry<List<SQLField>, Link> e = iter.next();
                    // don't use e.getValue() since it can be null
                    final SQLTable linkTable = e.getKey().get(0).getTable();
                    if (oldTablesInScope.contains(linkTable))
                        iter.remove();
                }
                for (final Iterator<Entry<SQLTable, Set<Link>>> iter = this.foreignLinks.entrySet()
                        .iterator(); iter.hasNext();) {
                    final Entry<SQLTable, Set<Link>> e = iter.next();
                    final SQLTable linkTable = e.getKey().getTable();
                    if (oldTablesInScope.contains(linkTable))
                        iter.remove();
                }
            }
        }

        if (clearGraph) {
            this.getGraphP().removeAllVertices(oldTablesInScope);
            assert this.getGraphP().vertexSet().size() == 0 && this.getGraphP().edgeSet().size() == 0;
        } else {
            // Removing a vertex also removes edges, so check that we also refresh referent
            // tables otherwise they won't have any foreign links anymore which is wrong if
            // removedTable was just renamed
            // Also the cache is only cleared for tables in scope, meaning that the cache for
            // those referent tables will be incoherent with the actual graph
            final Collection<SQLTable> removedTables = org.openconcerto.utils.CollectionUtils
                    .subtract(oldTablesInScope, newTablesInScope);
            for (final SQLTable removedTable : removedTables) {
                final Set<SQLTable> referentTables = getReferentTables(removedTable);
                // MAYBE add option to refresh needed tables instead of failing
                if (!oldTablesInScope.containsAll(referentTables)) {
                    throw new IllegalStateException(
                            removedTable + " has been removed but some of its referents won't be refreshed : "
                                    + org.openconcerto.utils.CollectionUtils.subtract(referentTables,
                                            oldTablesInScope));
                }
            }
            this.getGraphP().removeAllVertices(removedTables);

            // remove links that will be refreshed.
            final Set<Link> linksToRemove = new HashSet<Link>();
            for (final SQLTable t : org.openconcerto.utils.CollectionUtils.intersection(oldTablesInScope,
                    newTablesInScope)) {
                linksToRemove.addAll(this.getGraphP().outgoingEdgesOf(t));
            }
            this.getGraphP().removeAllEdges(linksToRemove);
        }

        // add new tables (and existing but it's OK graph vertices is a set)
        Graphs.addAllVertices(this.getGraphP(), newTablesInScope);
    }
    final TablesMap fromXML = toRefresh.getFromXML();
    final TablesMap fromJDBC = toRefresh.getFromJDBC();
    if (fromXML.size() > 0) {
        final DBItemFileCache dir = this.getFileCache();
        try {
            if (dir != null) {
                Log.get().config("for mapping " + this + " trying xmls in " + dir);
                final long t1 = System.currentTimeMillis();
                res = this.mapFromXML(fromXML);
                // remove what was loaded
                fromXML.removeAll(res);
                final long t2 = System.currentTimeMillis();
                Log.get().config("XML took " + (t2 - t1) + "ms for mapping the graph of " + this.base.getName()
                        + "." + res);
            }
        } catch (Exception e) {
            SQLBase.logCacheError(dir, e);
            this.deleteGraphFiles();
        }
        // add to JDBC what wasn't loaded
        fromJDBC.merge(fromXML);
    }
    if (!fromJDBC.isEmpty()) {
        final long t1 = System.currentTimeMillis();
        for (final Entry<String, Set<String>> e : fromJDBC.entrySet()) {
            final String rootName = e.getKey();
            final Set<String> tableNames = e.getValue();
            final DBRoot r = this.base.getRoot(rootName);
            // first try to map the whole root at once
            if (!this.map(r, tableNames)) {
                // if this isn't supported use standard JDBC
                for (final String table : tableNames) {
                    this.map(r, table, null);
                }
            }
            this.save(r);
        }
        final long t2 = System.currentTimeMillis();
        Log.get()
                .config("JDBC took " + (t2 - t1) + "ms for mapping the graph of " + this.base + "." + fromJDBC);
    }
    return res;
}