java.util.concurrent.locks.Lock Java Examples

The following examples show how to use java.util.concurrent.locks.Lock. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RocksRawKVStore.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void resetSequence(final byte[] seqKey, final KVStoreClosure closure) {
    final Timer.Context timeCtx = getTimeContext("RESET_SEQUENCE");
    final Lock readLock = this.readWriteLock.readLock();
    readLock.lock();
    try {
        this.db.delete(this.sequenceHandle, seqKey);
        setSuccess(closure, Boolean.TRUE);
    } catch (final Exception e) {
        LOG.error("Fail to [RESET_SEQUENCE], [key = {}], {}.", BytesUtil.toHex(seqKey),
            StackTraceUtil.stackTrace(e));
        setCriticalError(closure, "Fail to [RESET_SEQUENCE]", e);
    } finally {
        readLock.unlock();
        timeCtx.stop();
    }
}
 
Example #2
Source File: AppContext.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor for AppContext.  This method is <i>not</i> public,
 * nor should it ever be used as such.  The proper way to construct
 * an AppContext is through the use of SunToolkit.createNewAppContext.
 * A ThreadGroup is created for the new AppContext, a Thread is
 * created within that ThreadGroup, and that Thread calls
 * SunToolkit.createNewAppContext before calling anything else.
 * That creates both the new AppContext and its EventQueue.
 *
 * @param   threadGroup     The ThreadGroup for the new AppContext
 * @see     sun.awt.SunToolkit
 * @since   1.2
 */
AppContext(ThreadGroup threadGroup) {
    numAppContexts.incrementAndGet();

    this.threadGroup = threadGroup;
    threadGroup2appContext.put(threadGroup, this);

    this.contextClassLoader =
         AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            });

    // Initialize push/pop lock and its condition to be used by all the
    // EventQueues within this AppContext
    Lock eventQueuePushPopLock = new ReentrantLock();
    put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
    Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
    put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
 
Example #3
Source File: BlockManagerMaster.java    From nemo with Apache License 2.0 6 votes vote down vote up
/**
 * Manages the block information when a executor is removed.
 *
 * @param executorId the id of removed executor.
 * @return the set of task groups have to be recomputed.
 */
public Set<String> removeWorker(final String executorId) {
  final Set<String> taskGroupsToRecompute = new HashSet<>();
  LOG.warn("Worker {} is removed.", new Object[]{executorId});

  final Lock writeLock = lock.writeLock();
  writeLock.lock();
  try {
    // Set committed block states to lost
    getCommittedBlocksByWorker(executorId).forEach(blockId -> {
      onBlockStateChanged(blockId, BlockState.State.LOST, executorId);
      // producerTaskGroupForPartition should always be non-empty.
      final Set<String> producerTaskGroupForPartition = getProducerTaskGroupIds(blockId);
      producerTaskGroupForPartition.forEach(taskGroupsToRecompute::add);
    });

    return taskGroupsToRecompute;
  } finally {
    writeLock.unlock();
  }
}
 
Example #4
Source File: CandidateFilterFactory.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
/**
 * @return an implementation of {@link CandidateFilter} chosen per above. It will be non-null.
 * 
 * @param Y item-feature matrix
 * @param yReadLock read lock that should be acquired to access {@code Y}
 */
public static CandidateFilter buildCandidateFilter(FastByIDMap<float[]> Y, Lock yReadLock) {
  Preconditions.checkNotNull(Y);
  if (!Y.isEmpty()) {
    yReadLock.lock();
    try {
      String candidateFilterCustomClassString = System.getProperty("model.candidateFilter.customClass");
      if (candidateFilterCustomClassString != null) {
        return ClassUtils.loadInstanceOf(candidateFilterCustomClassString,
                                         CandidateFilter.class,
                                         new Class<?>[]{FastByIDMap.class},
                                         new Object[]{Y});
      }
      // LSH is a bit of a special case, handled here
      if (LocationSensitiveHash.LSH_SAMPLE_RATIO < 1.0) {
        return new LocationSensitiveHash(Y);
      }
    } finally {
      yReadLock.unlock();
    }
  }
  return new IdentityCandidateFilter(Y);    
}
 
Example #5
Source File: RpcWebuiServiceImpl.java    From hasting with MIT License 6 votes vote down vote up
@Override
public List<RpcService> search(String namespace, String keyword) {
	LinkedList<RpcService> result = new LinkedList<RpcService>();
	Lock lock = readwriteLock.readLock();
	try{
		lock.lock();
		Set<RpcService> services = namespaceServices.get(namespace);
		if(services!=null){
			for(RpcService service:services){
				if(keyword==null||keyword.length()<1){
					result.add(service);
				}else{
					String name = service.getName().toLowerCase();
					String key = keyword.toLowerCase();
					if(name.contains(key)){
						result.add(service);
					}
				}
			}
		}
	}finally{
		lock.unlock();
	}
	return result;
}
 
Example #6
Source File: Basic.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static Reader interruptibleReaderView(final StampedLock sl,
                                      final long timeout,
                                      final TimeUnit unit,
                                      final Phaser gate) {
    return new Reader("InterruptibleReaderView") { public void run() {
        if (gate != null ) toTheStartingGate(gate);
        final Lock rl = sl.asReadLock();

        try {
            if (timeout < 0)
                rl.lockInterruptibly();
            else
                rl.tryLock(timeout, unit);
            stamp(1L);  // got the lock
            check(sl.isReadLocked());
            check(!sl.isWriteLocked());
        } catch (Throwable x) { thrown(x);
        } finally { if (stamp() != 0L) rl.unlock(); } }};
}
 
Example #7
Source File: Identity.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
public static Set<Identity> getAll()
{
    Lock readLock = GLOBAL_IDENTITY_MAP_LOCK.readLock();

    Set<Identity> result = new TreeSet<>();
    try
    {
        readLock.lock();
        result.addAll(GLOBAL_IDENTITY_MAP.values());
    }
    finally
    {
        readLock.unlock();
    }
    return result;
}
 
Example #8
Source File: Utils.java    From RxStore with Apache License 2.0 6 votes vote down vote up
static void runInWriteLock(ReentrantReadWriteLock readWriteLock, ThrowingRunnable runnable) {
  Lock readLock = readWriteLock.readLock();
  int readCount = readWriteLock.getWriteHoldCount() == 0 ? readWriteLock.getReadHoldCount() : 0;

  for (int i = 0; i < readCount; i++) {
    readLock.unlock();
  }

  Lock writeLock = readWriteLock.writeLock();
  writeLock.lock();

  try {
    runnable.run();
  } catch (Exception e) {
    throw new RuntimeException(e);
  } finally {
    for (int i = 0; i < readCount; i++) {
      readLock.lock();
    }
    writeLock.unlock();
  }
}
 
Example #9
Source File: ReadWriteMap.java    From talent-aio with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** 
 * @see java.util.Map#values()
 * 
 * @return
 * @重写人: tanyaowu
 * @重写时间: 2017年2月8日 上午9:46:16
 * 
 */
@Override
public Collection<V> values()
{
	Lock lock = readLock;
	try
	{
		lock.lock();
		return map.values();
	} catch (Exception e)
	{
		throw e;
	} finally
	{
		lock.unlock();
	}
}
 
Example #10
Source File: TaskWrapperManager.java    From Aria with Apache License 2.0 6 votes vote down vote up
/**
 * 获取普通任务的Wrapper
 *
 * @return 创建失败,返回null;成功返回{@link DTaskWrapper}或者{@link UTaskWrapper}
 */
public <TW extends AbsTaskWrapper> TW getNormalTaskWrapper(Class<TW> clazz, long taskId) {
  final Lock lock = this.lock;
  lock.lock();
  try {

    AbsTaskWrapper wrapper = cache.get(convertKey(clazz, taskId));
    if (wrapper == null || wrapper.getClass() != clazz) {
      INormalTEFactory factory = chooseNormalFactory(clazz);
      if (factory == null) {
        ALog.e(TAG, "任务实体创建失败");
        return null;
      }
      wrapper = factory.create(taskId);
      putTaskWrapper(wrapper);
    }
    return (TW) wrapper;
  } finally {
    lock.unlock();
  }
}
 
Example #11
Source File: NettyClientAsync.java    From jstorm with Apache License 2.0 6 votes vote down vote up
private void initFlowCtrl(Map conf, Set<Integer> sourceTasks, Set<Integer> targetTasks) {
    isBackpressureEnable = ConfigExtension.isBackpressureEnable(conf);
    flowCtrlAwaitTime = ConfigExtension.getNettyFlowCtrlWaitTime(conf);
    cacheSize = ConfigExtension.getNettyFlowCtrlCacheSize(conf) != null ? ConfigExtension.getNettyFlowCtrlCacheSize(conf) : messageBatchSize;

    targetTasksUnderFlowCtrl = new HashMap<>();
    targetTasksToLocks = new HashMap<>();
    targetTasksCache = new HashMap<>();
    for (Integer task : targetTasks) {
        targetTasksUnderFlowCtrl.put(task, false);
        Lock lock = new ReentrantLock();
        targetTasksToLocks.put(task, new Pair<>(lock, lock.newCondition()));
    }

    Set<Integer> tasks = new HashSet<Integer>(sourceTasks);
    tasks.add(0); // add task-0 as default source task
    for (Integer sourceTask : tasks) {
        Map<Integer, MessageBuffer> messageBuffers = new HashMap<>();
        for (Integer targetTask : targetTasks) {
            messageBuffers.put(targetTask, new MessageBuffer(cacheSize));
        }
        targetTasksCache.put(sourceTask, messageBuffers);
    }
}
 
Example #12
Source File: MemoryManager.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int getAssociatedSlotSize(final int addr) {
    // BLZG-1658 MemoryManager should know when it has been closed (operation is not protected against concurrent close()).
       final Lock lock = m_allocationLock.readLock();
   	lock.lock();
	try {
		assertOpen();
		
		final SectorAllocator sector = getSector(addr);

		final int offset = SectorAllocator.getSectorOffset(addr);

		return sector.getPhysicalSize(offset);
	} finally {
       	lock.unlock();
       }
}
 
Example #13
Source File: RocksRawKVStore.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public void get(final byte[] key, @SuppressWarnings("unused") final boolean readOnlySafe,
                final KVStoreClosure closure) {
    final Timer.Context timeCtx = getTimeContext("GET");
    final Lock readLock = this.readWriteLock.readLock();
    readLock.lock();
    try {
        final byte[] value = this.db.get(key);
        setSuccess(closure, value);
    } catch (final Exception e) {
        LOG.error("Fail to [GET], key: [{}], {}.", BytesUtil.toHex(key), StackTraceUtil.stackTrace(e));
        setFailure(closure, "Fail to [GET]");
    } finally {
        readLock.unlock();
        timeCtx.stop();
    }
}
 
Example #14
Source File: GlobalTimeoutJobCleanupCoordinator.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Inspecting timeout jobs, updating their status to failure.
 * 
 * @param cleanupFinalizerLockName
 * @throws InterruptedException
 */
private void doInspectForTimeoutStopAndCleanup(String cleanupFinalizerLockName) throws InterruptedException {
	Lock lock = lockManager.getLock(keyFormat(cleanupFinalizerLockName));
	try {
		// Cleanup timeout jobs on this node, nodes that do not
		// acquire lock are on ready in place.
		if (lock.tryLock()) {
			long begin = System.currentTimeMillis();
			//int count = taskHistoryDao.updateStatus(config.getBuild().getJobTimeoutSec());
			int count = pipelineHistoryDao.updateStatus(config.getBuild().getJobTimeoutSec());
			if (count > 0) {
				log.info("Updated pipeline timeout jobs, with jobTimeoutSec:{}, count:{}, cost: {}ms",
						config.getBuild().getJobTimeoutSec(), count, (currentTimeMillis() - begin));
			}
		} else {
			log.debug("Skip cleanup jobs ... jobTimeoutSec:{}", config.getBuild().getJobTimeoutSec());
		}
	} catch (Throwable ex) {
		log.error("Failed to timeout jobs cleanup", ex);
	} finally {
		lock.unlock();
	}

}
 
Example #15
Source File: SynapseAppDeployer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Acquires the lock
 *
 * @param axisConfig AxisConfiguration instance
 * @return Lock instance
 */
protected Lock getLock(AxisConfiguration axisConfig) {
    Parameter p = axisConfig.getParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
    if (p != null) {
        return (Lock) p.getValue();
    } else {
        log.warn(ServiceBusConstants.SYNAPSE_CONFIG_LOCK + " is null, Recreating a new lock");
        Lock lock = new ReentrantLock();
        try {
            axisConfig.addParameter(ServiceBusConstants.SYNAPSE_CONFIG_LOCK, lock);
            return lock;
        } catch (AxisFault axisFault) {
            log.error("Error while setting " + ServiceBusConstants.SYNAPSE_CONFIG_LOCK);
        }
    }

    return null;
}
 
Example #16
Source File: MemoryManager.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void activateTx() {
	final Lock lock = m_allocationLock.writeLock();
	lock.lock();
    try {
        assertOpen(); // BLZG-1658 MemoryManager should know when it has been closed
        m_activeTxCount++;
        if(log.isInfoEnabled())
            log.info("#activeTx="+m_activeTxCount);
        
        // check for new session protection
        if (m_activeTxCount == 1 && m_contexts.isEmpty()) {
        	acquireSessions();
        }
    } finally {
    	lock.unlock();
    }
}
 
Example #17
Source File: EventQueue.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public EventQueue() {
    for (int i = 0; i < NUM_PRIORITIES; i++) {
        queues[i] = new Queue();
    }
    /*
     * NOTE: if you ever have to start the associated event dispatch
     * thread at this point, be aware of the following problem:
     * If this EventQueue instance is created in
     * SunToolkit.createNewAppContext() the started dispatch thread
     * may call AppContext.getAppContext() before createNewAppContext()
     * completes thus causing mess in thread group to appcontext mapping.
     */

    appContext = AppContext.getAppContext();
    pushPopLock = (Lock)appContext.get(AppContext.EVENT_QUEUE_LOCK_KEY);
    pushPopCond = (Condition)appContext.get(AppContext.EVENT_QUEUE_COND_KEY);
}
 
Example #18
Source File: MethodTimer.java    From client_java with Apache License 2.0 6 votes vote down vote up
@Around("timeable()")
public Object timeMethod(ProceedingJoinPoint pjp) throws Throwable {
    String key = pjp.getSignature().toLongString();

    Summary summary;
    final Lock r = summaryLock.readLock();
    r.lock();
    try {
        summary = summaries.get(key);
    } finally {
        r.unlock();
    }

    if (summary == null) {
        summary = ensureSummary(pjp, key);
    }

    final Summary.Timer t = summary.startTimer();

    try {
        return pjp.proceed();
    } finally {
        t.observeDuration();
    }
}
 
Example #19
Source File: Basic.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static Reader interruptibleReaderView(final StampedLock sl,
                                      final long timeout,
                                      final TimeUnit unit,
                                      final Phaser gate) {
    return new Reader("InterruptibleReaderView") { public void run() {
        if (gate != null ) toTheStartingGate(gate);
        final Lock rl = sl.asReadLock();

        try {
            if (timeout < 0)
                rl.lockInterruptibly();
            else
                rl.tryLock(timeout, unit);
            stamp(1L);  // got the lock
            check(sl.isReadLocked());
            check(!sl.isWriteLocked());
        } catch (Throwable x) { thrown(x);
        } finally { if (stamp() != 0L) rl.unlock(); } }};
}
 
Example #20
Source File: StratosManagerServiceImpl.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void addUsedCartridgeGroupsInApplications(String applicationName, String[] cartridgeGroupNames) {
    Lock lock = null;
    try {
        lock = StratosManagerContext.getInstance().acquireCartridgeGroupsApplicationsWriteLock();
        StratosManagerContext.getInstance().addUsedCartridgeGroupsInApplications(applicationName, cartridgeGroupNames);
        StratosManagerContext.getInstance().persist();
    } finally {
        if (lock != null) {
            StratosManagerContext.getInstance().releaseWriteLock(lock);
        }
    }
}
 
Example #21
Source File: AbstractConnection.java    From heisenberg with Apache License 2.0 5 votes vote down vote up
/**
 * 打开写事件
 */
private void enableWrite() {
    final Lock lock = this.keyLock;
    lock.lock();
    try {
        SelectionKey key = this.processKey;
        key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
    } finally {
        lock.unlock();
    }
    processKey.selector().wakeup();
}
 
Example #22
Source File: ModulaSymbolCache.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public Iterable<IModuleSymbol> moduleIterator() {
	Lock readLock = instanceLock.readLock();
	try{
		readLock.lock();
		return new Iterable<IModuleSymbol>() {
			@Override
			public Iterator<IModuleSymbol> iterator() {
				return new ArrayList<IModuleSymbol>(modulePath2ModuleSymbol.values()).iterator();
			}
		};
	}
	finally{
		readLock.unlock();
	}
}
 
Example #23
Source File: TxVersionedCache.java    From kareldb with Apache License 2.0 5 votes vote down vote up
public boolean replace(Comparable[] oldKey, Comparable[] oldValue,
                       Comparable[] newKey, Comparable[] newValue) {
    Iterable<ReadWriteLock> locks = striped.bulkGet(ImmutableList.of(Arrays.asList(oldKey), Arrays.asList(newKey)));
    List<Lock> writeLocks = Streams.streamOf(locks)
        .map(ReadWriteLock::writeLock)
        .collect(Collectors.toList());
    writeLocks.forEach(Lock::lock);
    try {
        KarelDbTransaction tx = KarelDbTransaction.currentTransaction();
        // Ensure the value hasn't changed
        List<VersionedValue> oldValues = snapshotFilter.get(tx, oldKey);
        VersionedValue oldVersionedValue = oldValues.size() > 0 ? oldValues.get(0) : null;
        if (oldVersionedValue == null || !Arrays.equals(oldValue, oldVersionedValue.getValue())) {
            throw new IllegalStateException("Previous value has changed");
        }
        if (Arrays.equals(oldKey, newKey)) {
            addWriteSetElement(tx, new KarelDbCellId(cache, newKey, tx.getWriteTimestamp()));
            cache.put(newKey, tx.getWriteTimestamp(), newValue);
            return true;
        } else {
            List<VersionedValue> newValues = snapshotFilter.get(tx, newKey);
            if (newValues.size() > 0) {
                throw new IllegalStateException("Primary key constraint violation: " + Arrays.toString(newKey));
            }
            addWriteSetElement(tx, new KarelDbCellId(cache, oldKey, tx.getWriteTimestamp()));
            addWriteSetElement(tx, new KarelDbCellId(cache, newKey, tx.getWriteTimestamp()));
            cache.remove(oldKey, tx.getWriteTimestamp());
            cache.put(newKey, tx.getWriteTimestamp(), newValue);
            return true;
        }
    } finally {
        writeLocks.forEach(Lock::unlock);
    }
}
 
Example #24
Source File: ModulaAstCache.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private void doClear() {
	Lock writeLock = instanceLock.writeLock();
	try{
		writeLock.lock();
		storage.clear();
	}
	finally{
		writeLock.unlock();
	}
}
 
Example #25
Source File: ConfigManager.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the configuration and writes it to the {@link #getConfigFile() file}, overwriting
 * the previous content of the file.
 *
 * @param config the new configuration
 * @param createBackup if true a .bak file is copied from the original as a backup
 * @throws Exception if the new configuration cannot be written to the file
 */
public void updateConfiguration(Configuration config, boolean createBackup) throws Exception {
    if (config == null) {
        throw new IllegalArgumentException("config must not be null");
    }
    Lock lock = this.configurationLock.writeLock();
    lock.lock();
    try {
        save(this.configFile, config, createBackup);
        this.configuration = new Configuration(config);
    } finally {
        lock.unlock();
    }
}
 
Example #26
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private void unregisterHandler(Thing thing, ThingHandlerFactory thingHandlerFactory) {
    Lock lock = getLockForThing(thing.getUID());
    try {
        lock.lock();
        if (isHandlerRegistered(thing)) {
            doUnregisterHandler(thing, thingHandlerFactory);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #27
Source File: BestFirst.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
private void lockConditionSafeleyWhileExpandingNode(final Lock l, final BackPointerPath<N, A, V> node) throws AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, InterruptedException {
	try {
		l.lockInterruptibly();
	} catch (InterruptedException e) { // if we are interrupted during a wait, we must still conduct a controlled shutdown
		this.bfLogger.debug("Received an interrupt while waiting for {} to become available.", l);
		Thread.currentThread().interrupt();
		this.checkTerminationAndUnregisterFromExpand(node);
	}
}
 
Example #28
Source File: RocksKVIterator.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void seekForPrev(final byte[] target) {
    final Lock readLock = this.dbReadLock;
    readLock.lock();
    try {
        ensureSafety();
        it.seekForPrev(target);
    } finally {
        readLock.unlock();
    }
}
 
Example #29
Source File: LockUtils.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 使用锁同步执行代码
 *
 * @param lock   -同步锁
 * @param action -执行操作
 */
public static void runWithLock(Lock lock, Runnable action) {
    lock.lock();
    try {
        action.run();
    } finally {
        lock.unlock();
    }
}
 
Example #30
Source File: ObligationService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds a collection of obligation handler to the list of registered handlers
 * 
 * This method waits until a write lock is obtained for the set of registered obligation handlers.
 * 
 * @param handlers the collection of handlers to add to the list of registered handlers.
 */
public void addObligationhandler(Collection<BaseObligationHandler> handlers) {
    if (handlers == null || handlers.isEmpty()) {
        return;
    }

    Lock writeLock = rwLock.writeLock();
    writeLock.lock();
    try {
        obligationHandlers.addAll(handlers);
    } finally {
        writeLock.unlock();
    }
}