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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #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: SoftRefFileCache.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
public @NonNullable Set<String> keySet() {
    Set<String> kset = map.keySet();
    String[] list = null;
    Lock cacheLock = CacheManager.inst.readLock(this);
    cacheLock.lock();
    try {
        list = CacheFileUtils.inst.getCacheDirList(this.name);
    } finally {
        cacheLock.unlock();
    }
    if (list != null)
        kset.addAll(Arrays.asList(list));
    return kset;
}
 
Example #22
Source File: RpcWebuiServiceImpl.java    From hasting with MIT License 5 votes vote down vote up
@Override
public List<String> getNamespaces() {
	List<String> list = new ArrayList<String>();
	Lock lock = readwriteLock.readLock();
	try{
		lock.lock();
		Set<String> keys = md5ConfigCache.keySet();
		if(keys!=null){
			list.addAll(keys);
		}
	}finally{
		lock.unlock();
	}
	return list;
}
 
Example #23
Source File: AbstractLockedOffHeapHashMap.java    From offheap-store with Apache License 2.0 5 votes vote down vote up
@Override
public V fill(K key, V value) {
  Lock l = writeLock();
  l.lock();
  try {
    return super.fill(key, value);
  } finally {
    l.unlock();
  }
}
 
Example #24
Source File: OpenSslSessionStats.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the number of times a client presented a ticket derived from an older key,
 * and we upgraded to the primary key.
 */
public long ticketKeyRenew() {
    Lock readerLock = context.ctxLock.readLock();
    readerLock.lock();
    try {
        return SSLContext.sessionTicketKeyRenew(context.ctx);
    } finally {
        readerLock.unlock();
    }
}
 
Example #25
Source File: HiveMQExtensions.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a callback that is executed after an extension was stopped.
 *
 * @param callback the consumer of the stopped extension.
 */
public void addAfterExtensionStopCallback(final @NotNull Consumer<HiveMQExtension> callback) {
    final Lock lock = afterPluginStopCallbacksLock.writeLock();
    try {
        lock.lock();
        afterPluginStopCallbacks.add(callback);
    } finally {
        lock.unlock();
    }
}
 
Example #26
Source File: HiveMQExtensions.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
private void notifyBeforeExtensionStopCallbacks(final @NotNull HiveMQExtension extension) {
    final Lock lock = beforePluginStopCallbacksLock.readLock();
    try {
        lock.lock();
        for (final Consumer<HiveMQExtension> callback : beforePluginStopCallbacks) {
            callback.accept(extension);
        }
    } finally {
        lock.unlock();
    }
}
 
Example #27
Source File: ModulaSymbolCache.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public void addModule(IModuleSymbol moduleSymbol) {
	Lock writeLock = instanceLock.writeLock();
	IModuleSymbol oldSymbol = null;
	try{
		writeLock.lock();
		oldSymbol = modulePath2ModuleSymbol.put(moduleSymbol.getKey(), moduleSymbol);
		if (ID_DEBUG_PRINT_CACHE_MODIFICATIONS) System.out.println(String.format("Added %s %s", moduleSymbol.getKey().moduleFile, new ModificationStamp()));
	}
	finally{
		writeLock.unlock();
	}
	notifyListenersSymbolAdded(oldSymbol, moduleSymbol);
}
 
Example #28
Source File: BlockManagerMaster.java    From nemo with Apache License 2.0 5 votes vote down vote up
/**
 * @param blockId the id of the block.
 * @return the {@link BlockState} of a block.
 */
@VisibleForTesting
BlockState getBlockState(final String blockId) {
  final Lock readLock = lock.readLock();
  readLock.lock();
  try {
    return blockIdToMetadata.get(blockId).getBlockState();
  } finally {
    readLock.unlock();
  }
}
 
Example #29
Source File: OperationInfo.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Add a new parameter to the set of arguments for this operation.
 *
 * @param parameter The new parameter descriptor
 */
public void addParameter(ParameterInfo parameter) {

    Lock writeLock = parametersLock.writeLock();
    writeLock.lock();
    try {
        ParameterInfo results[] = new ParameterInfo[parameters.length + 1];
        System.arraycopy(parameters, 0, results, 0, parameters.length);
        results[parameters.length] = parameter;
        parameters = results;
        this.info = null;
    } finally {
        writeLock.unlock();
    }
}
 
Example #30
Source File: LockInstance.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public LockInstance setLock(Lock lock){
    if(getLock()!=null){
        throw new IllegalStateException("Lock already exist");
    }
    this.lock=lock;
    return this;
}