Example usage for java.util.concurrent.locks ReadWriteLock readLock

List of usage examples for java.util.concurrent.locks ReadWriteLock readLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReadWriteLock readLock.

Prototype

Lock readLock();

Source Link

Document

Returns the lock used for reading.

Usage

From source file:Main.java

public static void main(String[] args) {
    System.out.println("read to write test");
    ReadWriteLock lock = new ReentrantReadWriteLock();

    lock.readLock().lock(); // get our own read lock
    lock.writeLock().lock(); // upgrade to write lock
    System.out.println("passed");
}

From source file:org.apache.directory.fortress.core.impl.UsoUtil.java

/**
 *
 * @return handle to simple digraph containing user ou hierarchies.
 *///  w  ww.  j av a  2  s.c o m
private static SimpleDirectedGraph<String, Relationship> getGraph(String contextId) {
    ReadWriteLock hierLock = HierUtil.getLock(contextId, HierUtil.Type.USO);
    String key = getKey(contextId);

    try {
        hierLock.readLock().lock();
        SimpleDirectedGraph<String, Relationship> graph = (SimpleDirectedGraph<String, Relationship>) usoCache
                .get(key);

        if (graph == null) {
            try {
                hierLock.readLock().unlock();
                hierLock.writeLock().lock();

                // TODO: determine why this (code that was commented out) creates a deadlock:
                //graph = ( SimpleDirectedGraph<String, Relationship> ) usoCache.get( key );

                //if ( graph == null )
                //{
                graph = loadGraph(contextId);
                //}
                hierLock.readLock().lock();
            } finally {
                hierLock.writeLock().unlock();
            }
        }

        return graph;
    } finally {
        hierLock.readLock().unlock();
    }
}

From source file:org.apache.directory.fortress.core.impl.PsoUtil.java

/**
 * @param contextId maps to sub-tree in DIT, for example ou=contextId, dc=jts, dc = com.
 * @return handle to simple digraph containing perm ou hierarchies.
 *//*from ww  w . java  2 s  .  co m*/
private static SimpleDirectedGraph<String, Relationship> getGraph(String contextId) {
    ReadWriteLock hierLock = HierUtil.getLock(contextId, HierUtil.Type.PSO);
    String key = getKey(contextId);

    try {
        hierLock.readLock().lock();
        SimpleDirectedGraph<String, Relationship> graph = (SimpleDirectedGraph<String, Relationship>) psoCache
                .get(key);

        if (graph == null) {
            try {
                hierLock.readLock().unlock();
                hierLock.writeLock().lock();

                // TODO: determine why this (code that was commented out) creates a deadlock:
                //graph = ( SimpleDirectedGraph<String, Relationship> ) psoCache.get( key );

                //if ( graph == null )
                //{
                graph = loadGraph(contextId);
                //}

                hierLock.readLock().lock();
            } finally {
                hierLock.writeLock().unlock();
            }
        }

        return graph;
    } finally {
        hierLock.readLock().unlock();
    }
}

From source file:org.apache.directory.fortress.core.impl.AdminRoleUtil.java

/**
 * Read this ldap record,{@code cn=Hierarchies, ou=OS-P} into this entity, {@link Hier}, before loading into this collection class,{@code org.jgrapht.graph.SimpleDirectedGraph}
 * using 3rd party lib, <a href="http://www.jgrapht.org/">JGraphT</a>.
 *
 * @param contextId maps to sub-tree in DIT, for example ou=contextId, dc=jts, dc = com.
 * @return handle to simple digraph containing adminRole hierarchies.
 *//*from w  w w.  ja v  a2 s .co m*/
private static SimpleDirectedGraph<String, Relationship> getGraph(String contextId) {
    ReadWriteLock hierLock = HierUtil.getLock(contextId, HierUtil.Type.ARLE);
    String key = getKey(contextId);

    try {
        hierLock.readLock().lock();
        SimpleDirectedGraph<String, Relationship> graph = (SimpleDirectedGraph<String, Relationship>) adminRoleCache
                .get(key);

        if (graph == null) {
            try {
                hierLock.readLock().unlock();
                hierLock.writeLock().lock();

                // TODO: determine why this (code that was commented out) creates a deadlock:
                //graph = ( SimpleDirectedGraph<String, Relationship> ) adminRoleCache.get( key );

                //if ( graph == null )
                //{
                graph = loadGraph(contextId);
                //}

                hierLock.readLock().lock();
            } finally {
                hierLock.writeLock().unlock();
            }
        }

        return graph;
    } finally {
        hierLock.readLock().unlock();
    }
}

From source file:org.apache.directory.fortress.core.impl.RoleUtil.java

/**
 *
 * @param contextId maps to sub-tree in DIT, for example ou=contextId, dc=jts, dc = com.
 * @return handle to simple digraph containing role hierarchies.
 *//* ww  w. jav a  2s  .  c  o  m*/
private static SimpleDirectedGraph<String, Relationship> getGraph(String contextId) {
    ReadWriteLock hierLock = HierUtil.getLock(contextId, HierUtil.Type.ROLE);
    String key = getKey(contextId);

    try {
        hierLock.readLock().lock();
        SimpleDirectedGraph<String, Relationship> graph = (SimpleDirectedGraph<String, Relationship>) roleCache
                .get(key);

        if (graph == null) {
            try {
                hierLock.readLock().unlock();
                hierLock.writeLock().lock();

                // TODO: determine why this (code that was commented out) creates a deadlock:
                //graph = ( SimpleDirectedGraph<String, Relationship> ) roleCache.get( key );

                //if ( graph == null )
                //{
                graph = loadGraph(contextId);
                //}

                hierLock.readLock().lock();
            } finally {
                hierLock.writeLock().unlock();
            }
        }

        return graph;
    } finally {
        hierLock.readLock().unlock();
    }
}

From source file:org.jactr.io.resolver.ASTResolver.java

/**
 * create a version of the model.with the option to generate just the model
 * header (fullResoltuion), or to filter out content when generating a full
 * dump/*  ww  w .  ja v  a 2 s  .  c o  m*/
 * 
 * @param model
 * @param fullResolution
 *          if false, just the model & parameters is generated. filters are
 *          ignored.
 * @param productionFilter
 * @param chunkTypeFilter
 * @param chunkFilter
 * @return
 */
static public CommonTree toAST(IModel model, boolean fullResolution, Predicate<IProduction> productionFilter,
        Predicate<IChunkType> chunkTypeFilter, Predicate<IChunk> chunkFilter) {
    if (productionFilter == null)
        productionFilter = p -> true;
    if (chunkTypeFilter == null)
        chunkTypeFilter = c -> true;
    if (chunkFilter == null)
        chunkFilter = c -> true;

    /**
     * lock so that we are the only one right now
     */
    ReadWriteLock lock = model.getLock();

    lock.readLock().lock();
    try {
        CommonTree md = _support.createModelTree(model.getName());

        // insert all the parameters
        setParameters(ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.PARAMETERS), model);

        if (fullResolution) {
            CommonTree modules = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.MODULES);
            for (IModule module : model.getModules()) {
                CommonTree modDesc = toAST(module);
                modules.addChild(modDesc);
            }

            // if full we add extensions, buffers, chunks, chunktype, and
            // productions
            CommonTree extensions = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.EXTENSIONS);

            for (IExtension extension : model.getExtensions()) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Generating AST for extension " + extension.getClass().getName());

                CommonTree ed = toAST(extension);

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Returned ast " + ed.toStringTree());

                extensions.addChild(ed);
            }
            // chunktypes will add the chunks for us
            CommonTree decWrapper = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.DECLARATIVE_MEMORY);
            Set<IChunkType> resolved = new HashSet<IChunkType>();
            List<CommonTree> chunkTypes = new ArrayList<CommonTree>();
            try {
                for (IChunkType ct : model.getDeclarativeModule().getChunkTypes().get())
                    if (chunkTypeFilter.test(ct)) {
                        List<CommonTree> chunkTypesList = toOrderedAST(ct, resolved, chunkTypeFilter,
                                chunkFilter);
                        chunkTypes.addAll(chunkTypesList);
                    }
            } catch (InterruptedException ie) {
                LOGGER.error("Interrupted ", ie);
            } catch (ExecutionException e) {
                LOGGER.error("Execution ", e);
            }

            // now we can dump them
            for (CommonTree ctNode : chunkTypes)
                decWrapper.addChild(ctNode);

            chunkTypes.clear();

            // productions
            CommonTree proWrapper = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.PROCEDURAL_MEMORY);
            try {
                for (IProduction p : model.getProceduralModule().getProductions().get()) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("generating AST for production " + p);
                    CommonTree pd = toAST(p);
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("returned ast " + pd.toStringTree());
                    proWrapper.addChild(pd);
                }
            } catch (InterruptedException ie) {
                LOGGER.error("Interrupted ", ie);
            } catch (ExecutionException e) {
                LOGGER.error("Execution ", e);
            }

            // buffers
            CommonTree buffersWrapper = ASTSupport.getFirstDescendantWithType(md, JACTRBuilder.BUFFERS);
            Map<String, CommonTree> chunkTypeNodes = ASTSupport.getMapOfTrees(decWrapper,
                    JACTRBuilder.CHUNK_TYPE);
            for (IActivationBuffer buffer : model.getActivationBuffers()) {
                buffersWrapper.addChild(toAST(buffer));
                /*
                 * since the chunks in the buffer aren't in the model, they won't be
                 * serialized correctly, so we grab them now and stick them under
                 * their respective chunktype
                 */
                for (IChunk source : buffer.getSourceChunks()) {
                    CommonTree sourceChunk = toAST(source, false);
                    CommonTree chunkType = chunkTypeNodes.get(source.getSymbolicChunk().getChunkType()
                            .getSymbolicChunkType().getName().toLowerCase());

                    if (chunkType != null)
                        ASTSupport.getFirstDescendantWithType(chunkType, JACTRBuilder.CHUNKS)
                                .addChild(sourceChunk);
                }
            }
        }
        return md;
    } finally {
        lock.readLock().unlock();
    }
}

From source file:com.cloudera.oryx.als.serving.ServerRecommender.java

private static float[] getFeatures(long longID, LongObjectMap<float[]> matrix, ReadWriteLock lock) {
    float[] features;
    Lock readLock = lock.readLock();
    readLock.lock();// w  w  w.j  a  v a  2  s  .  c o  m
    try {
        features = matrix.get(longID);
        if (features == null) {
            int numFeatures = countFeatures(matrix);
            if (numFeatures > 0) {
                features = new float[numFeatures];
                Lock writeLock = lock.writeLock();
                readLock.unlock();
                writeLock.lock();
                try {
                    matrix.put(longID, features);
                } finally {
                    readLock.lock();
                    writeLock.unlock();
                }
            }
        }
    } finally {
        readLock.unlock();
    }
    return features;
}

From source file:RWStripedHashSet.java

/**
 * Constructor//  w  ww  . java 2  s  .  c  o m
 * @param capacity Initial number of  buckets.
 */
public RWStripedHashSet(int capacity) {
    super(capacity);
    locks = new Lock[capacity];
    for (int j = 0; j < locks.length; j++) {
        locks[j] = new ReentrantLock();
    }
    ReadWriteLock rwLock = new ReentrantReadWriteLock();
    readLock = rwLock.readLock();
    writeLock = rwLock.writeLock();
}

From source file:org.alfresco.repo.content.replication.AggregatingContentStore.java

/**
 * Default constructor //  w w w.j a  v  a2  s  .  co  m
 */
public AggregatingContentStore() {
    ReadWriteLock storeLock = new ReentrantReadWriteLock();
    readLock = storeLock.readLock();
    writeLock = storeLock.writeLock();
}

From source file:org.sonar.core.dryrun.DryRunCache.java

public byte[] getDatabaseForDryRun(@Nullable Long projectId) {
    long notNullProjectId = projectId != null ? projectId.longValue() : 0L;
    ReadWriteLock rwl = getLock(notNullProjectId);
    try {//from ww w .j  ava 2  s  .c  o  m
        rwl.readLock().lock();
        if (!isCacheValid(projectId)) {
            // upgrade lock manually
            // must unlock first to obtain writelock
            rwl.readLock().unlock();
            rwl.writeLock().lock();
            // recheck
            if (!isCacheValid(projectId)) {
                generateNewDB(projectId);
            }
            // downgrade lock
            // reacquire read without giving up write lock
            rwl.readLock().lock();
            // unlock write, still hold read
            rwl.writeLock().unlock();
        }
        File dbFile = new File(getCacheLocation(projectId),
                lastTimestampPerProject.get(notNullProjectId) + DryRunDatabaseFactory.H2_FILE_SUFFIX);
        return fileToByte(dbFile);
    } finally {
        rwl.readLock().unlock();
    }
}