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

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

Introduction

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

Prototype

Lock writeLock();

Source Link

Document

Returns the lock used for writing.

Usage

From source file:org.apache.servicemix.jbi.cluster.engine.ClusterEndpointLoadTest.java

public void testLoadInOut() throws Exception {
    createRoute(Transacted.Jms, true, false, false);

    final int nbThreads = 10;
    final int nbExchanges = 10;
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    final CountDownLatch latch = new CountDownLatch(nbThreads);
    lock.writeLock().lock();
    for (int i = 0; i < nbThreads; i++) {
        new Thread() {
            public void run() {
                Channel client = null;
                try {
                    client = nmr1.createChannel();
                    lock.readLock().lock();
                    for (int i = 0; i < nbExchanges; i++) {
                        Exchange exchange = client.createExchange(Pattern.InOut);
                        exchange.getIn().setBody(new StringSource("<hello/>"));
                        exchange.setTarget(nmr1.getEndpointRegistry()
                                .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME)));
                        client.sendSync(exchange);
                        assertEquals(Status.Active, exchange.getStatus());
                        exchange.setStatus(Status.Done);
                        client.send(exchange);
                    }/*from  ww  w  .j  a va 2s.  co  m*/
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                    latch.countDown();
                    if (client != null) {
                        client.close();
                    }
                }
            }
        }.start();
    }

    cluster2.pause();
    lock.writeLock().unlock();
    Thread.sleep(0000);
    cluster2.resume();

    latch.await();

    receiver.assertExchangesReceived(nbThreads * nbExchanges * 2, TIMEOUT);
}

From source file:gridool.db.sql.ParallelSQLExecJob.java

private static void createMergeView(@Nonnull final Connection conn, @Nonnull final String ddl,
        @Nonnull final ReadWriteLock rwlock) throws GridException {
    if (LOG.isInfoEnabled()) {
        LOG.info("Create a merge view: \n" + ddl);
    }/*w  w  w.  j a v a2  s  .  c  om*/
    final Lock wlock = rwlock.writeLock();
    try {
        wlock.lock();
        JDBCUtils.update(conn, ddl);
    } catch (SQLException e) {
        String errmsg = "failed running a reduce query: " + ddl;
        LOG.error(errmsg, e);
        try {
            conn.rollback();
        } catch (SQLException rbe) {
            LOG.warn("Rollback failed", rbe);
        }
        throw new GridException(errmsg, e);
    } finally {
        wlock.unlock();
    }
}

From source file:org.apache.ambari.server.state.action.ActionImpl.java

public ActionImpl(ActionId id, long startTime) {
    super();/*from w w w  .j av  a2 s. c  om*/
    this.id = id;
    this.stateMachine = stateMachineFactory.make(this);
    ReadWriteLock rwLock = new ReentrantReadWriteLock();
    this.readLock = rwLock.readLock();
    this.writeLock = rwLock.writeLock();
    this.startTime = startTime;
    this.lastUpdateTime = -1;
    this.completionTime = -1;
}

From source file:org.apache.servicemix.jbi.cluster.engine.ClusterEndpointLoadTest.java

public void testLoadInOnly() throws Exception {
    createRoute(Transacted.Jms, true, false, true);

    final int nbThreads = 10;
    final int nbExchanges = 10;
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    final CountDownLatch latch = new CountDownLatch(nbThreads);
    final AtomicInteger id = new AtomicInteger();
    lock.writeLock().lock();
    for (int i = 0; i < nbThreads; i++) {
        new Thread() {
            public void run() {
                Channel client = null;
                try {
                    client = nmr1.createChannel();
                    lock.readLock().lock();
                    for (int i = 0; i < nbExchanges; i++) {
                        Exchange exchange = client.createExchange(Pattern.InOnly);
                        exchange.getIn()
                                .setBody(new StringSource("<hello id='" + id.getAndIncrement() + "'/>"));
                        exchange.setTarget(nmr1.getEndpointRegistry()
                                .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME)));
                        client.sendSync(exchange);
                        assertEquals(Status.Done, exchange.getStatus());
                    }/*from www. j a v  a  2 s  .  co  m*/
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                    latch.countDown();
                    if (client != null) {
                        client.close();
                    }
                }
            }
        }.start();
    }

    long t0, t1;

    t0 = System.currentTimeMillis();
    lock.writeLock().unlock();

    latch.await();

    receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT);

    t1 = System.currentTimeMillis();

    System.err.println("Elapsed time: " + (t1 - t0) + " ms");
    System.err.println("Throuput: " + (nbThreads * nbExchanges * 1000 / (t1 - t0)) + " messages/sec");
}

From source file:org.apache.servicemix.jbi.cluster.engine.ReconnectTest.java

public void testLoadInOnly() throws Exception {
    createRoute(Transacted.Jms, true, false, false);

    final int nbThreads = 10;
    final int nbExchanges = 10;
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    final CountDownLatch latch = new CountDownLatch(nbThreads);
    final AtomicInteger id = new AtomicInteger();
    lock.writeLock().lock();
    for (int i = 0; i < nbThreads; i++) {
        new Thread() {
            public void run() {
                Channel client = null;
                try {
                    client = nmr1.createChannel();
                    lock.readLock().lock();
                    for (int i = 0; i < nbExchanges; i++) {
                        Exchange exchange = client.createExchange(Pattern.InOnly);
                        exchange.getIn()
                                .setBody(new StringSource("<hello id='" + id.getAndIncrement() + "'/>"));
                        exchange.setTarget(nmr1.getEndpointRegistry()
                                .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME)));
                        client.sendSync(exchange);
                        assertEquals(Status.Done, exchange.getStatus());
                    }//from   ww w.  jav a 2  s .  c o  m
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                    latch.countDown();
                    if (client != null) {
                        client.close();
                    }
                }
            }
        }.start();
    }

    long t0, t1;

    cluster2.pause();

    t0 = System.currentTimeMillis();
    lock.writeLock().unlock();

    latch.await();

    broker.stop();
    cluster2.resume();

    Thread.sleep(500);
    broker = createBroker(false);

    receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT);
    //Thread.sleep(500);
    //receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT);

    t1 = System.currentTimeMillis();

    System.err.println("Elapsed time: " + (t1 - t0) + " ms");
    System.err.println("Throuput: " + (nbThreads * nbExchanges * 1000 / (t1 - t0)) + " messages/sec");
}

From source file:org.apache.ambari.resource.statemachine.ClusterImpl.java

public ClusterImpl(Cluster cluster, int revision) throws IOException {
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();
    this.stateMachine = stateMachineFactory.make(this);
    List<ServiceFSM> serviceImpls = new ArrayList<ServiceFSM>();
    for (String service : cluster.getClusterDefinition(revision).getEnabledServices()) {
        if (hasActiveRoles(cluster, service)) {
            ServiceImpl serviceImpl = new ServiceImpl(cluster.getComponentDefinition(service).getActiveRoles(),
                    this, service);

            serviceImpls.add(serviceImpl);
        }// w  w  w  .  ja  v  a 2 s  .  co  m
    }
    this.cls = cluster;
    this.services = serviceImpls;
}

From source file:org.jactr.entry.Main.java

public void cleanUp(ACTRRuntime runtime) {

    if (runtime.getConnector().isRunning())
        try {//from  w ww  .  j  a v a 2 s .c o  m
            runtime.getConnector().stop();
        } catch (Exception e) {
            LOGGER.error("Failed to shutdown connector ", e);
        }

    /*
     * detach the current controller before we exit
     */
    runtime.setController(null);

    /*
     * and clean up
     */
    ArrayList<IModel> toDispose = new ArrayList<IModel>();
    for (IModel model : new ArrayList<IModel>(runtime.getModels())) {
        runtime.removeModel(model);
        toDispose.add(model);
    }

    /*
     * will kill the background threads..
     */
    ExecutorServices.shutdown(0);

    /*
     * and dispose. Why not dispose with the remove? listeners may still be
     * active even after the runtime has stopped. We dispose after the service
     * has been shutdown, making sure that all work has been completed
     */
    for (IModel model : toDispose) {
        ReadWriteLock lock = model.getLock();
        lock.writeLock().lock();

        try {
            model.dispose();
        } catch (Exception e) {
            LOGGER.error(String.format("Failed to dispose of %s cleanly. ", model), e);
        } finally {
            lock.writeLock().unlock();
        }
    }
}

From source file:org.apache.giraph.ooc.data.OutOfCoreDataManager.java

/**
 * Offloads partition data of a given partition in the data store to disk
 *
 * @param partitionId id of the partition to offload its data
 * @param basePath path to offload the data to
 * @throws IOException/*from  w w w. j  a  va2s  . c o m*/
 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings("UL_UNRELEASED_LOCK_EXCEPTION_PATH")
public void offloadPartitionData(int partitionId, String basePath) throws IOException {
    ReadWriteLock rwLock = getPartitionLock(partitionId);
    rwLock.writeLock().lock();
    hasPartitionDataOnDisk.add(partitionId);
    rwLock.writeLock().unlock();
    offloadInMemoryPartitionData(partitionId, getPath(basePath, partitionId));
}

From source file:org.apache.hadoop.security.alias.JavaKeyStoreProvider.java

private JavaKeyStoreProvider(URI uri, Configuration conf) throws IOException {
    this.uri = uri;
    path = ProviderUtils.unnestUri(uri);
    fs = path.getFileSystem(conf);/*from   www  . j  a v  a 2 s. c o m*/
    // Get the password from the user's environment
    if (System.getenv().containsKey(CREDENTIAL_PASSWORD_NAME)) {
        password = System.getenv(CREDENTIAL_PASSWORD_NAME).toCharArray();
    }
    // if not in ENV get check for file
    if (password == null) {
        String pwFile = conf.get(KEYSTORE_PASSWORD_FILE_KEY);
        if (pwFile != null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            URL pwdFile = cl.getResource(pwFile);
            if (pwdFile != null) {
                InputStream is = pwdFile.openStream();
                try {
                    password = IOUtils.toString(is).trim().toCharArray();
                } finally {
                    is.close();
                }
            }
        }
    }
    if (password == null) {
        password = KEYSTORE_PASSWORD_DEFAULT.toCharArray();
    }
    try {
        keyStore = KeyStore.getInstance(SCHEME_NAME);
        if (fs.exists(path)) {
            // save off permissions in case we need to
            // rewrite the keystore in flush()
            FileStatus s = fs.getFileStatus(path);
            permissions = s.getPermission();

            keyStore.load(fs.open(path), password);
        } else {
            permissions = new FsPermission("700");
            // required to create an empty keystore. *sigh*
            keyStore.load(null, password);
        }
    } catch (KeyStoreException e) {
        throw new IOException("Can't create keystore", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("Can't load keystore " + path, e);
    } catch (CertificateException e) {
        throw new IOException("Can't load keystore " + path, e);
    }
    ReadWriteLock lock = new ReentrantReadWriteLock(true);
    readLock = lock.readLock();
    writeLock = lock.writeLock();
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.LocalizedResource.java

public LocalizedResource(LocalResourceRequest rsrc, Dispatcher dispatcher) {
    this.rsrc = rsrc;
    this.dispatcher = dispatcher;
    this.ref = new LinkedList<ContainerId>();

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    this.readLock = readWriteLock.readLock();
    this.writeLock = readWriteLock.writeLock();

    this.stateMachine = stateMachineFactory.make(this);
}