Example usage for java.util.concurrent.locks ReentrantReadWriteLock writeLock

List of usage examples for java.util.concurrent.locks ReentrantReadWriteLock writeLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantReadWriteLock writeLock.

Prototype

public ReentrantReadWriteLock.WriteLock writeLock() 

Source Link

Usage

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

private void updateSubscription(@NotNull Subscription subscription, @NotNull SSLSocketFactory sslSocketFactory)
        throws AzureCmdException {
    authDataLock.readLock().lock();/* w ww.  j a  v  a 2  s . c  o  m*/

    try {
        String subscriptionId = subscription.getId();
        ReentrantReadWriteLock subscriptionLock = getSubscriptionLock(subscriptionId, true);
        subscriptionLock.writeLock().lock();

        try {
            if (subscriptions.containsKey(subscriptionId)) {
                Subscription existingSubscription = subscriptions.get(subscriptionId);
                existingSubscription.setManagementCertificate(subscription.getManagementCertificate());
                existingSubscription.setServiceManagementUrl(subscription.getServiceManagementUrl());
            } else {
                subscriptions.put(subscriptionId, subscription);
            }

            setSSLSocketFactory(subscriptionId, sslSocketFactory);
            storeSubscriptions();
        } finally {
            subscriptionLock.writeLock().unlock();
        }
    } finally {
        authDataLock.readLock().unlock();
    }
}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

@NotNull
private <T, V extends Closeable> T requestAzureSDK(@NotNull final String subscriptionId,
        @NotNull final SDKRequestCallback<T, V> requestCallback,
        @NotNull final AzureSDKClientProvider<V> clientProvider) throws AzureCmdException {
    if (hasSSLSocketFactory(subscriptionId)) {
        try {/*  w  w w  .  ja v a2s .  c om*/
            Subscription subscription = getSubscription(subscriptionId);
            V client = clientProvider.getSSLClient(subscription);

            try {
                return requestCallback.execute(client);
            } finally {
                client.close();
            }
        } catch (Throwable t) {
            if (t instanceof AzureCmdException) {
                throw (AzureCmdException) t;
            } else if (t instanceof ExecutionException) {
                throw new AzureCmdException(t.getCause().getMessage(), t.getCause());
            }

            throw new AzureCmdException(t.getMessage(), t);
        }
    } else if (hasAccessToken()) {
        V client = null;
        try {
            client = clientProvider.getAADClient(subscriptionId, accessToken);
            return requestCallback.execute(client);
        } catch (Throwable throwable) {
            throw new AzureCmdException(throwable.getMessage(), throwable);
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                throw new AzureCmdException(e.getMessage(), e);
            }
        }
    } else {
        final UserInfo userInfo = getUserInfo(subscriptionId);
        PluginSettings settings = DefaultLoader.getPluginComponent().getSettings();

        com.microsoft.tooling.msservices.helpers.auth.RequestCallback<T> aadRequestCB = new com.microsoft.tooling.msservices.helpers.auth.RequestCallback<T>() {
            @NotNull
            @Override
            public T execute(@NotNull String accessToken) throws Throwable {
                if (!hasAccessToken(userInfo) || !accessToken.equals(getAccessToken(userInfo))) {
                    ReentrantReadWriteLock userLock = getUserLock(userInfo, true);
                    userLock.writeLock().lock();

                    try {
                        if (!hasAccessToken(userInfo) || !accessToken.equals(getAccessToken(userInfo))) {
                            setAccessToken(userInfo, accessToken);
                        }
                    } finally {
                        userLock.writeLock().unlock();
                    }
                }

                V client = clientProvider.getAADClient(subscriptionId, accessToken);

                try {
                    return requestCallback.execute(client);
                } finally {
                    client.close();
                }
            }
        };

        return aadManager.request(userInfo, settings.getAzureServiceManagementUri(),
                "Sign in to your Azure account", aadRequestCB);
    }
}

From source file:spade.storage.Neo4j.java

public static void index(String dbpath, boolean printProgress) {

    int totalThreads = Runtime.getRuntime().availableProcessors();
    final ConcurrentLinkedQueue<Node> nodeTaskQueue = new ConcurrentLinkedQueue<Node>();
    final ConcurrentLinkedQueue<Relationship> edgeTaskQueue = new ConcurrentLinkedQueue<Relationship>();
    final ReentrantReadWriteLock nodeRwlock = new ReentrantReadWriteLock();
    final ReentrantReadWriteLock edgeRwlock = new ReentrantReadWriteLock();
    final Index<Node> vertexIndex;
    final RelationshipIndex edgeIndex;
    System.out.println("Loading database...");
    File databaseFile = new File(dbpath);
    final GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(databaseFile)
            .setConfig(GraphDatabaseSettings.pagecache_memory,
                    "" + (Runtime.getRuntime().totalMemory() * 9) / 10)
            // .setConfig(GraphDatabaseSettings.keep_logical_logs, "false")
            .newGraphDatabase();//from   w w  w .j a  va  2 s.  co m

    System.out.println("Loaded");
    // clear already present indexes
    try (Transaction tx = graphDb.beginTx()) {
        graphDb.index().forNodes(spade.storage.Neo4j.VERTEX_INDEX).delete();
        tx.success();
    }

    try (Transaction tx = graphDb.beginTx()) {
        graphDb.index().forRelationships(spade.storage.Neo4j.EDGE_INDEX).delete();
        tx.success();
    }
    //

    System.out.println("Creating Indexing discriptors...");

    try (Transaction tx = graphDb.beginTx()) {
        vertexIndex = graphDb.index().forNodes(spade.storage.Neo4j.VERTEX_INDEX);
        tx.success();
    }

    try (Transaction tx = graphDb.beginTx()) {
        edgeIndex = graphDb.index().forRelationships(spade.storage.Neo4j.EDGE_INDEX);
        tx.success();
    }

    System.out.println("Created");

    class NodeIndexer implements Runnable {

        public void run() {

            Transaction tx = graphDb.beginTx();
            int counter = 0;
            try {
                while (!Thread.currentThread().isInterrupted()) {

                    if (counter < 10000) {
                        Node node = nodeTaskQueue.poll();
                        if (node == null) {
                            continue;
                        }

                        for (String key : node.getPropertyKeys()) {
                            vertexIndex.add(node, key, (String) node.getProperty(key));
                        }
                        node.setProperty(ID_STRING, node.getId());
                        vertexIndex.add(node, ID_STRING, Long.toString(node.getId()));

                        counter++;
                    }

                    if (counter > 1000 && nodeRwlock.writeLock().tryLock()) {
                        tx.success();
                        tx.close();
                        tx = graphDb.beginTx();
                        nodeRwlock.writeLock().unlock();
                        counter = 0;
                    }

                }

            } finally {
                // tx.success();
                tx.close();
                if (nodeRwlock.writeLock().isHeldByCurrentThread()) {
                    nodeRwlock.writeLock().unlock();
                }
            }
        }
    }

    class RelationshipIndexer implements Runnable {

        public void run() {

            Transaction tx = graphDb.beginTx();
            int counter = 0;
            try {
                while (!Thread.currentThread().isInterrupted()) {

                    if (counter < 10000) {
                        Relationship relationship = edgeTaskQueue.poll();
                        if (relationship == null) {
                            continue;
                        }

                        for (String key : relationship.getPropertyKeys()) {
                            edgeIndex.add(relationship, key, (String) relationship.getProperty(key));
                        }
                        relationship.setProperty(ID_STRING, relationship.getId());
                        edgeIndex.add(relationship, ID_STRING, Long.toString(relationship.getId()));

                        counter++;
                    }

                    if (counter > 1000 && edgeRwlock.writeLock().tryLock()) {
                        // tx.success();
                        tx.close();
                        tx = graphDb.beginTx();
                        edgeRwlock.writeLock().unlock();
                        counter = 0;
                    }

                }

            } finally {
                // tx.success();
                tx.close();
                if (edgeRwlock.writeLock().isHeldByCurrentThread()) {
                    edgeRwlock.writeLock().unlock();
                }
            }

        }
    }

    ArrayList<Thread> nodeWorkers = new ArrayList<Thread>();
    for (int i = 0; i < totalThreads / 2; i++) {
        Thread th = new Thread(new NodeIndexer());
        nodeWorkers.add(th);
        th.start();
    }

    ArrayList<Thread> edgeWorkers = new ArrayList<Thread>();
    for (int i = 0; i < totalThreads / 2; i++) {
        Thread th = new Thread(new RelationshipIndexer());
        edgeWorkers.add(th);
        th.start();
    }

    System.out.println("Counted Nodes and Relationships to index...");
    final long total;

    try (Transaction tx = graphDb.beginTx()) {
        total = Iterators.count(graphDb.getAllNodes().iterator())
                + Iterators.count(graphDb.getAllRelationships().iterator());
        tx.success();
    }
    System.out.println("done.\n");

    long percentageCompleted = 0;
    int count = 0;

    try (Transaction tx = graphDb.beginTx()) {

        // index nodes
        Iterator<Node> nodeIterator = graphDb.getAllNodes().iterator();
        Iterator<Relationship> edgeIterator = graphDb.getAllRelationships().iterator();

        while (edgeIterator.hasNext() || nodeIterator.hasNext()) {

            if (nodeIterator.hasNext() && nodeTaskQueue.size() < 10000) {
                nodeTaskQueue.add(nodeIterator.next());
                count = count + 1;
            }

            if (edgeIterator.hasNext() && edgeTaskQueue.size() < 10000) {
                edgeTaskQueue.add(edgeIterator.next());
                count = count + 1;
            }

            if (printProgress) {

                if (((count * 100) / total) > percentageCompleted) {
                    Runtime rt = Runtime.getRuntime();
                    long totalMemory = rt.totalMemory() / 1024 / 1024;
                    long freeMemory = rt.freeMemory() / 1024 / 1024;
                    long usedMemory = totalMemory - freeMemory;
                    System.out.print("| Cores: " + rt.availableProcessors() + " | Threads: " + totalThreads
                            + " | Heap (MB) - total: " + totalMemory + " , " + (freeMemory * 100) / totalMemory
                            + "% free"
                            // + " | Total Objects (nodes + relationships) to Index: " + total
                            + " | Indexing Object (nodes + relationships): " + count + " / " + total
                            + " | Completed: " + percentageCompleted + " %" + " |\r");
                }

                percentageCompleted = (count * 100) / total;
            }

        }

        tx.success();
    }

    System.out.println("\n\nIndexing completed. Waiting for queues to clear...");

    try {
        while (nodeTaskQueue.size() != 0 || edgeTaskQueue.size() != 0) {
            Thread.sleep(1000);
        }
    } catch (InterruptedException exception) {

    }

    System.out.println("Queues cleared. Threads teardown started...");

    for (int i = 0; i < totalThreads / 2; i++) {
        nodeWorkers.get(i).interrupt();
        try {
            nodeWorkers.get(i).join();
        } catch (InterruptedException exception) {

        }
    }

    for (int i = 0; i < totalThreads / 2; i++) {
        edgeWorkers.get(i).interrupt();
        try {
            edgeWorkers.get(i).join();
        } catch (InterruptedException exception) {

        }
    }

    System.out.println("Database shutdown started...");
    graphDb.shutdown();
}

From source file:org.opencms.loader.CmsJspLoader.java

/**
 * Updates a JSP page in the "real" file system in case the VFS resource has changed.<p>
 * /*from  www.  java 2  s  .  co m*/
 * Also processes the <code>&lt;%@ cms %&gt;</code> tags before the JSP is written to the real FS.
 * Also recursively updates all files that are referenced by a <code>&lt;%@ cms %&gt;</code> tag 
 * on this page to make sure the file actually exists in the real FS. 
 * All <code>&lt;%@ include %&gt;</code> tags are parsed and the name in the tag is translated
 * from the OpenCms VFS path to the path in the real FS. 
 * The same is done for filenames in <code>&lt;%@ page errorPage=... %&gt;</code> tags.<p>
 * 
 * @param resource the requested JSP file resource in the VFS
 * @param controller the controller for the JSP integration
 * @param updatedFiles a Set containing all JSP pages that have been already updated
 * 
 * @return the file name of the updated JSP in the "real" FS
 * 
 * @throws ServletException might be thrown in the process of including the JSP 
 * @throws IOException might be thrown in the process of including the JSP 
 * @throws CmsLoaderException if the resource type can not be read
 */
public String updateJsp(CmsResource resource, CmsFlexController controller, Set<String> updatedFiles)
        throws IOException, ServletException, CmsLoaderException {

    String jspVfsName = resource.getRootPath();
    String extension;
    boolean isHardInclude;
    int loaderId = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getLoaderId();
    if ((loaderId == CmsJspLoader.RESOURCE_LOADER_ID) && (!jspVfsName.endsWith(JSP_EXTENSION))) {
        // this is a true JSP resource that does not end with ".jsp"
        extension = JSP_EXTENSION;
        isHardInclude = false;
    } else {
        // not a JSP resource or already ends with ".jsp"
        extension = "";
        // if this is a JSP we don't treat it as hard include
        isHardInclude = (loaderId != CmsJspLoader.RESOURCE_LOADER_ID);
    }

    String jspTargetName = CmsFileUtil.getRepositoryName(m_jspWebAppRepository, jspVfsName + extension,
            controller.getCurrentRequest().isOnline());

    // check if page was already updated
    if (updatedFiles.contains(jspTargetName)) {
        // no need to write the already included file to the real FS more then once
        return jspTargetName;
    }

    String jspPath = CmsFileUtil.getRepositoryName(m_jspRepository, jspVfsName + extension,
            controller.getCurrentRequest().isOnline());

    File d = new File(jspPath).getParentFile();
    if ((d == null) || (d.exists() && !(d.isDirectory() && d.canRead()))) {
        CmsMessageContainer message = Messages.get().container(Messages.LOG_ACCESS_DENIED_1, jspPath);
        LOG.error(message.key());
        // can not continue
        throw new ServletException(message.key());
    }

    if (!d.exists()) {
        // create directory structure
        d.mkdirs();
    }
    ReentrantReadWriteLock readWriteLock = getFileLock(jspVfsName);
    try {
        // get a read lock for this jsp
        readWriteLock.readLock().lock();
        File jspFile = new File(jspPath);
        // check if the JSP must be updated
        boolean mustUpdate = false;
        long jspModificationDate = 0;
        if (!jspFile.exists()) {
            // file does not exist in real FS
            mustUpdate = true;
            // make sure the parent folder exists
            File folder = jspFile.getParentFile();
            if (!folder.exists()) {
                boolean success = folder.mkdirs();
                if (!success) {
                    LOG.error(org.opencms.db.Messages.get().getBundle()
                            .key(org.opencms.db.Messages.LOG_CREATE_FOLDER_FAILED_1, folder.getAbsolutePath()));
                }
            }
        } else {
            jspModificationDate = jspFile.lastModified();
            if (jspModificationDate <= resource.getDateLastModified()) {
                // file in real FS is older then file in VFS
                mustUpdate = true;
            } else if (controller.getCurrentRequest().isDoRecompile()) {
                // recompile is forced with parameter
                mustUpdate = true;
            } else {
                // check if update is needed
                if (controller.getCurrentRequest().isOnline()) {
                    mustUpdate = !m_onlineJsps.containsKey(jspVfsName);
                } else {
                    mustUpdate = !m_offlineJsps.containsKey(jspVfsName);
                }
                // check strong links only if update is needed
                if (mustUpdate) {
                    // update strong link dependencies
                    mustUpdate = updateStrongLinks(resource, controller, updatedFiles);
                }
            }
        }
        if (mustUpdate) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_WRITING_JSP_1, jspTargetName));
            }
            // jsp needs updating, acquire a write lock
            readWriteLock.readLock().unlock();
            readWriteLock.writeLock().lock();
            try {
                // check again if updating is still necessary as this might have happened while waiting for the write lock
                if (!jspFile.exists() || (jspModificationDate == jspFile.lastModified())) {
                    updatedFiles.add(jspTargetName);
                    byte[] contents;
                    String encoding;
                    try {
                        CmsObject cms = controller.getCmsObject();
                        contents = cms.readFile(resource).getContents();
                        // check the "content-encoding" property for the JSP, use system default if not found on path
                        encoding = cms.readPropertyObject(resource,
                                CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue();
                        if (encoding == null) {
                            encoding = OpenCms.getSystemInfo().getDefaultEncoding();
                        } else {
                            encoding = CmsEncoder.lookupEncoding(encoding.trim(), encoding);
                        }
                    } catch (CmsException e) {
                        controller.setThrowable(e, jspVfsName);
                        throw new ServletException(
                                Messages.get().getBundle().key(Messages.ERR_LOADER_JSP_ACCESS_1, jspVfsName),
                                e);
                    }

                    try {
                        // parse the JSP and modify OpenCms critical directives
                        contents = parseJsp(contents, encoding, controller, updatedFiles, isHardInclude);
                        if (LOG.isInfoEnabled()) {
                            // check for existing file and display some debug info
                            LOG.info(Messages.get().getBundle().key(Messages.LOG_JSP_PERMCHECK_4,
                                    new Object[] { jspFile.getAbsolutePath(), Boolean.valueOf(jspFile.exists()),
                                            Boolean.valueOf(jspFile.isFile()),
                                            Boolean.valueOf(jspFile.canWrite()) }));
                        }
                        // write the parsed JSP content to the real FS
                        synchronized (CmsJspLoader.class) {
                            // this must be done only one file at a time
                            FileOutputStream fs = new FileOutputStream(jspFile);
                            fs.write(contents);
                            fs.close();
                        }
                        if (controller.getCurrentRequest().isOnline()) {
                            m_onlineJsps.put(jspVfsName, Boolean.TRUE);
                        } else {
                            m_offlineJsps.put(jspVfsName, Boolean.TRUE);
                        }
                        if (LOG.isInfoEnabled()) {
                            LOG.info(Messages.get().getBundle().key(Messages.LOG_UPDATED_JSP_2, jspTargetName,
                                    jspVfsName));
                        }
                    } catch (FileNotFoundException e) {
                        throw new ServletException(Messages.get().getBundle()
                                .key(Messages.ERR_LOADER_JSP_WRITE_1, jspFile.getName()), e);
                    }
                }
            } finally {
                readWriteLock.readLock().lock();
                readWriteLock.writeLock().unlock();
            }
        }

        // update "last modified" and "expires" date on controller
        controller.updateDates(jspFile.lastModified(), CmsResource.DATE_EXPIRED_DEFAULT);
    } finally {
        //m_processingFiles.remove(jspVfsName);
        readWriteLock.readLock().unlock();
    }

    return jspTargetName;
}

From source file:jext2.JextReentrantReadWriteLock.java

@Override
public WriteLock writeLock() {
    final ReentrantReadWriteLock.WriteLock l = super.writeLock();
    return new WriteLock(this) {
        private static final long serialVersionUID = -4345682740953361177L;

        @Override// ww w .  j a v  a 2 s.  c  o m
        public int getHoldCount() {
            return l.getHoldCount();
        }

        @Override
        public boolean isHeldByCurrentThread() {
            return l.isHeldByCurrentThread();
        }

        @Override
        public void lock() {
            logIfLoggable("write-lock()");
            l.lock();
        }

        @Override
        public void lockInterruptibly() throws InterruptedException {
            logIfLoggable("write-lock-inter()");
            l.lockInterruptibly();
        }

        @Override
        public Condition newCondition() {
            return l.newCondition();
        }

        @Override
        public boolean tryLock() {
            logIfLoggable("write-trylock()");
            return l.tryLock();
        }

        @Override
        public boolean tryLock(long arg0, TimeUnit arg1) throws InterruptedException {
            logIfLoggable("write-trylock()");
            return l.tryLock(arg0, arg1);
        }

        @Override
        public void unlock() {
            logIfLoggable("write-unlock()");
            l.unlock();

        }
    };
}

From source file:syncthing.android.service.ServiceSettingsProvider.java

private long putTextSetting(String key, String val) {
    ReentrantReadWriteLock.WriteLock lock = mLock.writeLock();
    try {/*from   w w w .j  ava2  s  . c o m*/
        lock.lock();
        ContentValues cv = new ContentValues(2);
        cv.put(ServiceSettingsDB.SCHEMA.KEY, key);
        cv.put(ServiceSettingsDB.SCHEMA.TEXT_VAL, val);
        return mDB.getWritableDatabase().insertWithOnConflict(ServiceSettingsDB.SCHEMA.TABLE, null, cv,
                SQLiteDatabase.CONFLICT_REPLACE);
    } finally {
        lock.unlock();
    }
}

From source file:syncthing.android.service.ServiceSettingsProvider.java

private long putIntSetting(String key, int val) {
    ReentrantReadWriteLock.WriteLock lock = mLock.writeLock();
    try {//from   w  ww  .j  a  v a 2  s . c o m
        lock.lock();
        ContentValues cv = new ContentValues(2);
        cv.put(ServiceSettingsDB.SCHEMA.KEY, key);
        cv.put(ServiceSettingsDB.SCHEMA.INT_VAL, val);
        return mDB.getWritableDatabase().insertWithOnConflict(ServiceSettingsDB.SCHEMA.TABLE, null, cv,
                SQLiteDatabase.CONFLICT_REPLACE);
    } finally {
        lock.unlock();
    }
}

From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java

/**
 * Materialize project *specific* certificates in *local* filesystem in the *standard* directory
 *
 * @param userName Username of the user/*from   www  . j  a v  a 2  s  .c o  m*/
 * @param projectName Name of the Project
 * @throws IOException
 */
public void materializeCertificatesLocal(String userName, String projectName) throws IOException {
    MaterialKey key = new MaterialKey(userName, projectName);
    ReentrantReadWriteLock.WriteLock lock = null;
    try {
        lock = getWriteLockForKey(key);
        lock.lock();
        materializeLocalInternal(key, transientDir);
    } finally {
        lock.unlock();
    }
}

From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java

private ReentrantReadWriteLock.WriteLock getWriteLockForKey(MaterialKey key) {
    return getLockForKey(key, true).writeLock();
}

From source file:org.objectweb.proactive.core.remoteobject.RemoteObjectSet.java

/**
 * Sort the list of rro uris, using locks to prevent concurrent modification
 *//*w w  w.j av  a 2  s .  c o  m*/
private void sortProtocolsInternal() {
    ReentrantReadWriteLock.WriteLock wl = rwlock.writeLock();
    wl.lock();
    sortedrros = sortProtocols(rros.keySet(), defaultProtocolOrder, lastBenchmarkResults, defaultURI);
    wl.unlock();
}