下面列出了org.apache.http.impl.client.BasicResponseHandler#java.util.concurrent.locks.Lock 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @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);
}
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();
}
}
/**
* @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();
}
}
/**
* 获取普通任务的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();
}
}
@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();
}
}
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);
}
}
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();
}
}
@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();
}
}
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(); } }};
}
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);
}
/**
* 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;
}
/**
* 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();
}
}
@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();
}
}
@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();
}
}
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;
}
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(); } }};
}
/**
* 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);
}
/**
* 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();
}
}
@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;
}
@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);
}
}
}
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;
}
@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;
}
@Override
public V fill(K key, V value) {
Lock l = writeLock();
l.lock();
try {
return super.fill(key, value);
} finally {
l.unlock();
}
}
/**
* 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();
}
}
/**
* 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();
}
}
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();
}
}
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);
}
/**
* @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();
}
}
/**
* 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();
}
}
public LockInstance setLock(Lock lock){
if(getLock()!=null){
throw new IllegalStateException("Lock already exist");
}
this.lock=lock;
return this;
}