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:com.zimbra.cs.db.SQLite.java

@Override
void preOpen(Integer mboxId) {
    ZimbraLog.dbconn.trace("trying to lock mbox %d", mboxId);
    assert (checkLockMap(mboxId));
    ReentrantLock lock = lockMap.get(mboxId);
    if (lock == null) {
        lock = new ReentrantLock();
        ReentrantLock added = lockMap.putIfAbsent(mboxId, lock);
        if (added != null) {
            lock = added;//from   w  w  w .java2 s.  co  m
        }
    }
    boolean locked = false;
    long timeoutSecs = 180;
    //lock with timeout in case external call sites cause a deadlock
    //(e.g. one site locks some object before opening connection; another incorrectly locks same object after opening connection)
    //in case of timeout we'll fall through and let sqlite_busy retry handler sort it out
    try {
        locked = lock.tryLock(timeoutSecs, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    if (!locked) {
        ZimbraLog.dbconn.warn("Unable to get db lock for mbox %d", mboxId);
    } else {
        ZimbraLog.dbconn.trace("locked mbox %d", mboxId);
    }
}

From source file:dbseer.old.middleware.MiddlewareSocket.java

private boolean startMonitoringProcesses(boolean newStart) {
    if (newStart) {
        DBSeerGUI.liveMonitorInfo.reset();
    }//ww  w.  j  a va 2  s.c o m
    StreamClustering.LOCK = new ReentrantLock();
    logReceiver = new IncrementalLogReceiver(this.ip,
            DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator + DBSeerConstants.LIVE_DATASET_PATH);
    incrementalLogThread = new Thread(logReceiver);
    incrementalLogThread.start();

    logParser = new LogParser(txMap);
    logParserThread = new Thread(logParser);
    logParserThread.start();

    if (newStart || StreamClustering.getDBSCAN() == null) {
        IncrementalDBSCAN dbscan = new IncrementalDBSCAN(DBSeerConstants.DBSCAN_MIN_PTS,
                Math.sqrt(Transaction.DIFF_SCALE) / 5, DBSeerConstants.DBSCAN_INIT_PTS);
        StreamClustering.setDBSCAN(dbscan);
    }

    clusterRunnable = new ClusterRunnable();
    clusteringThread = new Thread(clusterRunnable);
    clusteringThread.start();

    File sysLogFile = new File(DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator
            + DBSeerConstants.LIVE_DATASET_PATH + File.separator + "log_exp_1.csv");
    File monitorFile = new File(DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator
            + DBSeerConstants.LIVE_DATASET_PATH + File.separator + "monitor");
    File datasetHeaderFile = new File(DBSeerGUI.userSettings.getDBSeerRootPath() + File.separator
            + DBSeerConstants.LIVE_DATASET_PATH + File.separator + "dataset_header.m");
    PrintWriter monitorWriter = null;
    try {
        monitorWriter = new PrintWriter(new FileWriter(monitorFile, true));
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    liveTransactionProcessor = new LiveTransactionProcessor(txMap, monitorWriter);
    liveTransactionProcessorThread = new Thread(liveTransactionProcessor);
    liveTransactionProcessorThread.start();

    TailerListener tailerListener = new LiveSystemLogTailerListener(txMap, monitorWriter, datasetHeaderFile,
            newStart);
    sysLogTailer = new Tailer(sysLogFile, tailerListener, 1000);
    sysLogTailerThread = new Thread(sysLogTailer);
    sysLogTailerThread.start();

    liveMonitor = new LiveMonitor();
    //      liveMonitor.start();

    if (newStart) {
        DBSeerGUI.isLiveDataReady = false;
        DBSeerGUI.liveDataset.clearTransactionTypes();
    }

    DBSeerGUI.isLiveMonitoring = true;

    return true;
}

From source file:org.gdg.frisbee.android.cache.ModelCache.java

private ReentrantLock getLockForDiskCacheEdit(String url) {
    synchronized (mDiskCacheEditLocks) {
        ReentrantLock lock = mDiskCacheEditLocks.get(url);
        if (null == lock) {
            lock = new ReentrantLock();
            mDiskCacheEditLocks.put(url, lock);
        }/*  ww w . j a  v  a 2s.c o  m*/
        return lock;
    }
}

From source file:com.android.exchange.service.PingSyncSynchronizer.java

public PingSyncSynchronizer(final Service service) {
    mLock = new ReentrantLock();
    mAccountStateMap = new LongSparseArray<AccountSyncState>();
    mService = service;//from  w  w  w .j a  v a2 s .  com
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

private static Deque<ServletRequest> getUsersDeque(final HttpSession session) {

    @SuppressWarnings("unchecked")
    Deque<ServletRequest> deque = (BlockingDeque<ServletRequest>) session.getAttribute(USER_REQUEST_QUEUE);

    // construct deque if necessary
    if (null == deque) {
        // it may be possible for duplicates across threads to be constructed here
        deque = new LinkedBlockingDeque<ServletRequest>(REQUEST_QUEUE_SIZE);
        session.setAttribute(USER_REQUEST_QUEUE, deque);
        session.setAttribute(USER_REQUEST_LOCK, new ReentrantLock());
    }// ww  w  .j  a  v a  2s.  c om

    return deque;
}

From source file:org.mule.test.oauth.internal.DancerConfigTestCase.java

@Test
public void multipleDancersShareTokensStore()
        throws MalformedURLException, InitialisationException, MuleException {
    final Map<String, Object> tokensStore = new HashMap<>();
    final MuleExpressionLanguage el = mock(MuleExpressionLanguage.class);

    final OAuthAuthorizationCodeDancerBuilder builder1 = service
            .authorizationCodeGrantTypeDancerBuilder(lockFactory, tokensStore, el);
    final OAuthAuthorizationCodeDancerBuilder builder2 = service
            .authorizationCodeGrantTypeDancerBuilder(lockFactory, tokensStore, el);

    builder1.clientCredentials("clientId", "clientSecret");
    builder2.clientCredentials("clientId", "clientSecret");

    minimalAuthCodeConfig(builder1);//from  w ww.j  av a2 s .c  o  m
    minimalAuthCodeConfig(builder2);

    builder1.resourceOwnerIdTransformer(roid -> "conn1-" + roid);
    builder2.resourceOwnerIdTransformer(roid -> "conn2-" + roid);

    final AuthorizationCodeOAuthDancer dancer1 = startDancer(builder1);
    final AuthorizationCodeOAuthDancer dancer2 = startDancer(builder2);

    final DefaultResourceOwnerOAuthContext contextOwnerConn1 = new DefaultResourceOwnerOAuthContext(
            new ReentrantLock(), "owner");
    final DefaultResourceOwnerOAuthContext contextOwnerConn2 = new DefaultResourceOwnerOAuthContext(
            new ReentrantLock(), "owner");
    tokensStore.put("conn1-owner", contextOwnerConn1);
    tokensStore.put("conn2-owner", contextOwnerConn2);

    assertThat(dancer1.getContextForResourceOwner("owner"), sameInstance(contextOwnerConn1));
    assertThat(dancer2.getContextForResourceOwner("owner"), sameInstance(contextOwnerConn2));
}

From source file:org.omnaest.utils.structure.collection.CollectionUtils.java

/**
 * Returns a view of the given {@link Collection} which uses a new {@link ReentrantLock} instance to synchronize all of its
 * methods//from www  . j  a  v  a 2 s .  c om
 * 
 * @param collection
 *          F@return
 */
public static <E> Collection<E> lockedByReentrantLock(Collection<E> collection) {
    Lock lock = new ReentrantLock();
    return new LockingCollectionDecorator<E>(collection, lock);
}

From source file:org.exoplatform.social.core.storage.impl.ActivityStreamStorageImpl.java

@Override
public void update(ProcessContext ctx) {
    final ReentrantLock lock = new ReentrantLock();
    ThreadLocal<Set<String>> idLocal = new ThreadLocal<Set<String>>();
    try {//w  w w  . j  a  v  a2  s  .  c om

        StreamProcessContext streamCtx = ObjectHelper.cast(StreamProcessContext.class, ctx);
        ExoSocialActivity activity = streamCtx.getActivity();
        ActivityEntity activityEntity = _findById(ActivityEntity.class, activity.getId());

        lock.lock(); // block until condition holds

        Collection<ActivityRef> references = activityEntity.getActivityRefs();
        Set<String> ids = new ConcurrentSkipListSet<String>();

        for (ActivityRef ref : references) {
            ids.add(ref.getId());
        }

        idLocal.set(ids);

        Set<String> idList = idLocal.get();
        if (idList.size() > 0) {
            for (String id : idList) {
                ActivityRef old = _findById(ActivityRef.class, id);
                LOG.debug("ActivityRef will be deleted: " + old.toString());
                ActivityRefListEntity refList = old.getDay().getMonth().getYear().getList();
                //
                if (refList.isOnlyUpdate(old, activity.getUpdated().getTime())) {
                    old.setName("" + activity.getUpdated().getTime());
                    old.setLastUpdated(activity.getUpdated().getTime());
                } else {
                    ActivityRef newRef = refList.getOrCreated(activity.getUpdated().getTime());
                    newRef.setLastUpdated(activity.getUpdated().getTime());
                    newRef.setActivityEntity(activityEntity);
                    getSession().remove(old);
                }

            }
        }

        // mentioners
        addMentioner(streamCtx.getMentioners(), activityEntity);
        //turnOffLock to get increase perf
        //turnOnUpdateLock = false;
    } catch (NodeNotFoundException ex) {
        LOG.warn("Probably was updated activity reference by another session");
        LOG.debug(ex.getMessage(), ex);
        //turnOnLock to avoid next exception
    } catch (ChromatticException ex) {
        Throwable throwable = ex.getCause();
        if (throwable instanceof ItemExistsException || throwable instanceof InvalidItemStateException
                || throwable instanceof PathNotFoundException) {
            LOG.warn("Probably was updated activity reference by another session");
            LOG.debug(ex.getMessage(), ex);
            //turnOnLock to avoid next exception
        } else {
            LOG.warn("Probably was updated activity reference by another session", ex);
            LOG.debug(ex.getMessage(), ex);
        }

    } finally {
        getSession().save();
        lock.unlock();
    }
}

From source file:com.tinspx.util.concurrent.DelayedSemaphoreTest.java

@SuppressWarnings("UnnecessaryUnboxing")
static void runTest(Executor executor, DelayedSemaphore ds, Ticker ticker, int threadCount, int acquisitions,
        Acquire acquire, Permits permits, Range<Integer> acquireRange, Release release,
        DelayConstraint constraint) throws InterruptedException {
    checkArgument(threadCount > 0);/*from ww  w .j a va  2s.  c o  m*/

    DelayTest.DelayTestBuilder builder = DelayTest.builder();
    builder.stop(new AtomicBoolean());
    builder.start(new CountDownLatch(threadCount));
    builder.lock(new ReentrantLock());
    builder.releaseTimes(new long[ds.permits()]);
    builder.acquisitions(acquisitions);
    builder.ticker(ticker).ds(ds);
    builder.acquire(acquire).permits(permits).permits(permits).acquireRange(acquireRange);
    builder.release(release);
    builder.delayConstraint(constraint);
    builder.tests(new MutableInt());
    builder.totalThreads(threadCount);

    DelayTest[] testers = new DelayTest[threadCount];
    for (int i = 0; i < threadCount; i++) {
        testers[i] = builder.thread(i).build();
        executor.execute(testers[i]);
    }
    for (int i = 0; i < threadCount; i++) {
        testers[i].complete.await();
    }
    String errorMsg = null;
    for (int i = 0; i < threadCount; i++) {
        if (testers[i].fail != null) {
            errorMsg = testers[i].fail;
            System.out.println(errorMsg);
            System.out.println();
        }
    }
    if (errorMsg != null) {
        fail(errorMsg);
    }

    assertEquals(threadCount * acquisitions, builder.tests.getValue().intValue());
    if (++testCount % 10 == 0) {
        System.out.printf("%d, Tests: %s\n", testCount, builder.tests);
    }
}

From source file:com.tinspx.util.concurrent.TimedSemaphoreTest.java

@SuppressWarnings("UnnecessaryUnboxing")
static void runTest(Executor executor, TimedSemaphore ts, Ticker ticker, int threadCount, int acquisitions,
        Acquire acquire, Permits permits) throws InterruptedException {
    checkArgument(threadCount > 0);/*w  w  w  .jav  a  2 s.c om*/

    DelayTest.DelayTestBuilder builder = DelayTest.builder();
    builder.stop(new AtomicBoolean());
    builder.start(new CountDownLatch(threadCount));
    builder.lock(new ReentrantLock());
    builder.acquisitions(acquisitions);
    builder.ticker(ticker).ts(ts);
    builder.acquire(acquire).permits(permits);
    builder.tests(new MutableInt());
    builder.totalThreads(threadCount);
    builder.history(new History(ts));

    DelayTest[] testers = new DelayTest[threadCount];
    for (int i = 0; i < threadCount; i++) {
        testers[i] = builder.thread(i).build();
        executor.execute(testers[i]);
    }
    for (int i = 0; i < threadCount; i++) {
        testers[i].complete.await();
    }
    String errorMsg = null;
    for (int i = 0; i < threadCount; i++) {
        if (testers[i].fail != null) {
            errorMsg = testers[i].fail;
            System.out.println(errorMsg);
            System.out.println();
        }
    }
    if (errorMsg != null) {
        fail(errorMsg);
    }

    assertEquals(threadCount * acquisitions, builder.tests.getValue().intValue());
    if (++testCount % 10 == 0) {
        System.out.printf("%d, Tests: %s\n", testCount, builder.tests);
    }
}