Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

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

Prototype

public ReentrantLock() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:org.apache.sling.scripting.sightly.impl.engine.UnitLoader.java

/**
 * Create a render unit from the given resource
 *
 * @param scriptResource the resource/* w ww .  j a  v a2  s . c o  m*/
 * @param bindings       the bindings
 * @param renderContext  the rendering context
 * @return the render unit
 */
public RenderUnit createUnit(Resource scriptResource, Bindings bindings, RenderContextImpl renderContext) {
    Lock lock = null;
    try {
        SourceIdentifier sourceIdentifier = obtainIdentifier(scriptResource);
        Object obj;
        ResourceMetadata resourceMetadata = scriptResource.getResourceMetadata();
        String encoding = resourceMetadata.getCharacterEncoding();
        if (encoding == null) {
            encoding = sightlyEngineConfiguration.getEncoding();
        }
        SlingHttpServletResponse response = (SlingHttpServletResponse) bindings.get(SlingBindings.RESPONSE);
        response.setCharacterEncoding(encoding);
        ResourceResolver adminResolver = renderContext.getScriptResourceResolver();
        if (needsUpdate(sourceIdentifier)) {
            synchronized (activeWrites) {
                String sourceFullPath = sourceIdentifier.getSourceFullPath();
                lock = activeWrites.get(sourceFullPath);
                if (lock == null) {
                    lock = new ReentrantLock();
                    activeWrites.put(sourceFullPath, lock);
                }
                lock.lock();
            }
            Resource javaClassResource = createClass(adminResolver, sourceIdentifier, bindings, encoding,
                    renderContext);
            obj = sightlyJavaCompilerService.compileSource(javaClassResource,
                    sourceIdentifier.getFullyQualifiedName());
        } else {
            obj = sightlyJavaCompilerService.getInstance(adminResolver, null,
                    sourceIdentifier.getFullyQualifiedName());
        }
        if (!(obj instanceof RenderUnit)) {
            throw new SightlyException("Class is not a RenderUnit instance");
        }
        return (RenderUnit) obj;
    } finally {
        if (lock != null) {
            lock.unlock();
        }
    }
}

From source file:me.xiaopan.android.spear.download.HttpClientImageDownloader.java

/**
 * ?URL?????//from ww  w.j  a  v a2s.co m
 * @param url ?
 * @return URL?
 */
public synchronized ReentrantLock getUrlLock(String url) {
    ReentrantLock urlLock = urlLocks.get(url);
    if (urlLock == null) {
        urlLock = new ReentrantLock();
        urlLocks.put(url, urlLock);
    }
    return urlLock;
}

From source file:org.compass.needle.terracotta.transaction.processor.TerracottaTransactionProcessorFactory.java

public void configure(CompassSettings settings) throws CompassException {
    this.settings = settings;
    batchJobsSize = settings.getSettingAsInt(TerracottaTransactionProcessorEnvironment.BATCH_JOBS_SIZE, 5);
    batchJobTimeout = settings//from w  w  w  . j  a  va2  s .  c om
            .getSettingAsTimeInMillis(TerracottaTransactionProcessorEnvironment.BATCH_JOBS_SIZE, 100);
    if (logger.isDebugEnabled()) {
        logger.debug("Terracotta Transaction Processor blocking batch size is [" + batchJobsSize
                + "] with timeout of [" + batchJobTimeout + "ms]");
    }
    nonBlockingBatchSize = settings
            .getSettingAsInt(TerracottaTransactionProcessorEnvironment.NON_BLOCKING_BATCH_JOBS_SIZE, 5);
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Terracotta Transaction Processor non blocking batch size is [" + nonBlockingBatchSize + "]");
    }
    holder.getInitializationLock().lock();
    try {
        for (String subIndex : searchEngineFactory.getIndexManager().getSubIndexes()) {
            BlockingQueue<TransactionJobs> subIndexJobs = holder.getJobsPerSubIndex().get(subIndex);
            if (subIndexJobs == null) {
                subIndexJobs = new LinkedBlockingQueue<TransactionJobs>();
                holder.getJobsPerSubIndex().put(subIndex, subIndexJobs);
            }
            Lock processorLock = holder.getProcessorLocks().get(subIndex);
            if (processorLock == null) {
                processorLock = new ReentrantLock();
                holder.getProcessorLocks().put(subIndex, processorLock);
            }
        }
    } finally {
        holder.getInitializationLock().unlock();
    }
    if (settings.getSettingAsBoolean(TerracottaTransactionProcessorEnvironment.PROCESS, true)) {
        String[] subIndexesSetting = StringUtils.commaDelimitedListToStringArray(
                settings.getSetting(TerracottaTransactionProcessorEnvironment.SUB_INDEXES));
        if (subIndexesSetting.length == 0) {
            subIndexesSetting = null;
        }
        String[] aliasesSetting = StringUtils.commaDelimitedListToStringArray(
                settings.getSetting(TerracottaTransactionProcessorEnvironment.ALIASES));
        if (aliasesSetting.length == 0) {
            aliasesSetting = null;
        }
        String[] subIndexes = searchEngineFactory.getIndexManager().calcSubIndexes(subIndexesSetting,
                aliasesSetting, null);
        logger.info("Terracotta Transaction Processor Worker started. Sub indexes to process: "
                + Arrays.toString(subIndexes));
        for (String subIndex : subIndexes) {
            TerracottaProcessor processor = new TerracottaProcessor(subIndex,
                    holder.getJobsPerSubIndex().get(subIndex));
            searchEngineFactory.getExecutorManager().submit(processor);
            currentProcessors.put(subIndex, processor);
        }
    } else {
        logger.info(
                "Terracotta transaction processor will only submit transactions to be processed (none worker mode)");
    }
}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

public ConfigurationServiceImpl() {
    runtimeFlags = new HashMap<String, Boolean>();
    lock = new ReentrantReadWriteLock();

    eventTimer = new Timer("Configuration Event Timer", true);
    eventLock = new ReentrantLock();
}

From source file:org.apache.stratos.common.clustering.impl.HazelcastDistributedObjectProvider.java

/**
 * Acquires a distributed lock if clustering is enabled, else acquires a local reentrant lock and
 * returns the lock object.//w ww.  ja  v  a2  s  .c o  m
 *
 * @param object
 * @return
 */
@Override
public Lock acquireLock(Object object) {
    if (isClustered()) {
        return acquireDistributedLock(object);
    } else {
        Lock lock = locksMap.get(object);
        if (lock == null) {
            synchronized (object) {
                if (lock == null) {
                    lock = new ReentrantLock();
                    locksMap.put(object, lock);
                }
            }
        }
        lock.lock();
        return lock;
    }
}

From source file:com.inmobi.grill.driver.hive.HiveDriver.java

public HiveDriver() throws GrillException {
    this.sessionLock = new ReentrantLock();
    grillToHiveSession = new HashMap<String, SessionHandle>();
    connectionExpiryThread.setDaemon(true);
    connectionExpiryThread.setName("HiveDriver-ConnectionExpiryThread");
    connectionExpiryThread.start();/*from   w w  w  .ja  va2 s .  c  o m*/
    LOG.info("Hive driver inited");
}

From source file:org.apache.hadoop.net.unix.TestDomainSocketWatcher.java

@Test(timeout = 300000)
public void testStressInterruption() throws Exception {
    final int SOCKET_NUM = 250;
    final ReentrantLock lock = new ReentrantLock();
    final DomainSocketWatcher watcher = newDomainSocketWatcher(10);
    final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>();
    final AtomicInteger handled = new AtomicInteger(0);

    final Thread adderThread = new Thread(new Runnable() {
        @Override/*  www. java 2s  . c  o m*/
        public void run() {
            try {
                for (int i = 0; i < SOCKET_NUM; i++) {
                    DomainSocket pair[] = DomainSocket.socketpair();
                    watcher.add(pair[1], new DomainSocketWatcher.Handler() {
                        @Override
                        public boolean handle(DomainSocket sock) {
                            handled.incrementAndGet();
                            return true;
                        }
                    });
                    lock.lock();
                    try {
                        pairs.add(pair);
                    } finally {
                        lock.unlock();
                    }
                    TimeUnit.MILLISECONDS.sleep(1);
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    final Thread removerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            final Random random = new Random();
            try {
                while (handled.get() != SOCKET_NUM) {
                    lock.lock();
                    try {
                        if (!pairs.isEmpty()) {
                            int idx = random.nextInt(pairs.size());
                            DomainSocket pair[] = pairs.remove(idx);
                            if (random.nextBoolean()) {
                                pair[0].close();
                            } else {
                                watcher.remove(pair[1]);
                            }
                            TimeUnit.MILLISECONDS.sleep(1);
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });

    adderThread.start();
    removerThread.start();
    TimeUnit.MILLISECONDS.sleep(100);
    watcher.watcherThread.interrupt();
    Uninterruptibles.joinUninterruptibly(adderThread);
    Uninterruptibles.joinUninterruptibly(removerThread);
    Uninterruptibles.joinUninterruptibly(watcher.watcherThread);
}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

public KiWiConnection(KiWiPersistence persistence, KiWiDialect dialect, CacheManager cacheManager)
        throws SQLException {
    this.cacheManager = cacheManager;
    this.dialect = dialect;
    this.persistence = persistence;
    this.commitLock = new ReentrantLock();
    this.literalLock = new ReentrantLock();
    this.uriLock = new ReentrantLock();
    this.bnodeLock = new ReentrantLock();
    this.batchCommit = dialect.isBatchSupported();
    this.deletedStatementsLog = BloomFilter.create(Funnels.longFunnel(), 100000);
    this.transactionId = getNextSequence();

    initCachePool();/*from   www . j ava2  s .c o m*/
    initStatementCache();
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests a successful asynchronous request where the implementation of the 
 * {@link AsyncHandler#onSuccess(HttpResponse, Object)} callback throws an exception.</p> 
 *  //w  w w  .  j a  v  a 2 s .c o m
 * @since 1.3.0
 */
@Test
public final void testAsyncSuccessCallbackError() throws InterruptedException {

    String subpath = "/successcallbackerror";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncSuccessCallbackError(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:org.asnelt.derandom.ProcessingFragment.java

/**
 * Constructor for initializing the processing fragment. Generates a HistoryBuffer, a
 * RandomManager and an ExecutorService.
 *//*from  w ww  . ja  v a  2 s.co  m*/
public ProcessingFragment() {
    super();
    predictionLength = 0;
    autoDetect = false;
    inputUri = null;
    inputReader = null;
    outputWriter = null;
    missingUpdate = false;
    inputSelection = 0;
    inputTaskLength = 0;
    processingDesirable = true;
    serverPort = 0;
    clientSocket = null;
    synchronizationObject = this;
    historyBuffer = new HistoryBuffer(0);
    randomManager = new RandomManager();
    // Handler for processing user interface updates
    handler = new Handler(Looper.getMainLooper());
    processingExecutor = Executors.newSingleThreadExecutor();
    serverExecutor = Executors.newSingleThreadExecutor();
    connectionLock = new ReentrantLock();
    disconnected = connectionLock.newCondition();
    serverFuture = null;
}