本文整理汇总了Java中java.util.concurrent.locks.Lock类的典型用法代码示例。如果您正苦于以下问题:Java Lock类的具体用法?Java Lock怎么用?Java Lock使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Lock类属于java.util.concurrent.locks包,在下文中一共展示了Lock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: count
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
int count(Predicate<PeerInfo> predicate) {
int numberOfConnectedPeers = 0;
Lock lock = readWriteLock.readLock();
try {
lock.lock();
for (PeerInfo peer : peers.values()) {
if (predicate.test(peer)) {
numberOfConnectedPeers++;
}
}
} finally {
lock.unlock();
}
return numberOfConnectedPeers;
}
示例2: put
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* Adds the given object to the store. Technically this method only adds the object if it does not already exist in
* the store. If it does this method simply increments the reference count of the object.
*
* @param object the object to add to the store, may be null
*
* @return the index that may be used to later retrieve the object or null if the object was null
*/
public String put(T object) {
if (object == null) {
return null;
}
Lock writeLock = rwLock.writeLock();
writeLock.lock();
try {
String index = Integer.toString(object.hashCode());
StoredObjectWrapper objectWrapper = objectStore.get(index);
if (objectWrapper == null) {
objectWrapper = new StoredObjectWrapper(object);
objectStore.put(index, objectWrapper);
}
objectWrapper.incremementReferenceCount();
return index;
} finally {
writeLock.unlock();
}
}
示例3: generateAvatar
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
private String generateAvatar(String primaryName, String secondaryName) {
String encoded = Hex.encodeHexString((primaryName + ":" + AvatarGenerator.version()).getBytes());
if (StringUtils.isBlank(primaryName))
primaryName = "?";
if (StringUtils.isBlank(secondaryName))
secondaryName = primaryName;
File avatarFile = new File(Bootstrap.getSiteDir(), "avatars/generated/" + encoded);
if (!avatarFile.exists()) {
Lock avatarLock = LockUtils.getLock("generated-avatar:" + encoded);
avatarLock.lock();
try {
String letters = getLetter(primaryName);
BufferedImage bi = AvatarGenerator.generate(letters, secondaryName);
FileUtils.createDir(avatarFile.getParentFile());
ImageIO.write(bi, "PNG", avatarFile);
} catch (NoSuchAlgorithmException | IOException e) {
throw new RuntimeException(e);
} finally {
avatarLock.unlock();
}
}
return AVATARS_BASE_URL + "generated/" + encoded;
}
示例4: tryLock
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* 锁
*
* @param lock 锁
* @param timeout 超时时间
* <li>>0 等待超时时间</li>
* <li>=0 无限等待</li>
* <li><0 无限等待</li>
* @return 剩余的超时时间
* <li>>0 锁成功,timeout>0,剩余超时时间</li>
* <li>0 锁成功,timeout=0</li>
* <li>-1 锁成功,timeout<0</li>
*
*/
public static long tryLock(final Lock lock, final long timeout) {
long time;
if (timeout > 0) {
time = JSFContext.systemClock.now();
try {
if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
time = timeout - (JSFContext.systemClock.now() - time);
if (time > 0) {
return time;
}else{
lock.unlock();
}
}
return LOCK_FAIL;
} catch (InterruptedException e) {
return LOCK_FAIL;
}
} else {
lock.lock();
return timeout == 0 ? 0 : -1;
}
}
示例5: processObligations
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* Processes the obligations within the effective XACML policy.
*
* This method waits until a read lock is obtained for the set of registered obligation handlers.
*
* @param context current processing context
*
* @throws ObligationProcessingException thrown if there is a problem evaluating an obligation
*/
public void processObligations(ObligationProcessingContext context) throws ObligationProcessingException {
Lock readLock = rwLock.readLock();
readLock.lock();
try {
Iterator<BaseObligationHandler> handlerItr = obligationHandlers.iterator();
Map<String, ObligationType> effectiveObligations = preprocessObligations(context);
BaseObligationHandler handler;
while (handlerItr.hasNext()) {
handler = handlerItr.next();
if (effectiveObligations.containsKey(handler.getObligationId())) {
handler.evaluateObligation(context, effectiveObligations.get(handler.getObligationId()));
}
}
} finally {
readLock.unlock();
}
}
示例6: getChangesToInitial
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
@Override
public Vector getChangesToInitial() {
Vector ret = new Vector();
Lock lock = currentSolution().getLock().readLock();
lock.lock();
try {
for (Lecture lecture: currentSolution().getModel().variables()) {
if (!ToolBox.equals(lecture.getInitialAssignment(),currentSolution().getAssignment().getValue(lecture))) {
RecordedAssignment a = new RecordedAssignment(this,(Placement)lecture.getInitialAssignment(),currentSolution().getAssignment().getValue(lecture));
if (lecture.getInitialAssignment()!=null) {
a.getBefore().setDetails(new ClassAssignmentDetails(this,lecture,(Placement)lecture.getInitialAssignment(),false));
}
if (currentSolution().getAssignment().getValue(lecture)!=null) {
a.getAfter().setDetails(new ClassAssignmentDetails(this,lecture,false));
}
ret.addElement(a);
}
}
} finally {
lock.unlock();
}
return ret;
}
示例7: get
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* Gets a registered object by its index.
*
* @param index the index of an object previously registered, may be null
*
* @return the registered object or null if no object is registered for that index
*/
public T get(String index) {
if (index == null) {
return null;
}
Lock readLock = rwLock.readLock();
readLock.lock();
try {
StoredObjectWrapper objectWrapper = objectStore.get(index);
if (objectWrapper != null) {
return objectWrapper.getObject();
}
return null;
} finally {
readLock.unlock();
}
}
示例8: getRealm
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* Return the Realm with which this Container is associated. If there is
* no associated Realm, return the Realm associated with our parent
* Container (if any); otherwise return <code>null</code>.
*/
@Override
public Realm getRealm() {
Lock l = realmLock.readLock();
try {
l.lock();
if (realm != null)
return (realm);
if (parent != null)
return (parent.getRealm());
return null;
} finally {
l.unlock();
}
}
示例9: getDistributedLock
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
@Override
public Lock getDistributedLock(Object key) throws IllegalStateException {
validateKey(key);
lockCheckReadiness();
checkForLimitedOrNoAccess();
if (!this.scope.isGlobal()) {
throw new IllegalStateException(
LocalizedStrings.DistributedRegion_DISTRIBUTION_LOCKS_ARE_ONLY_SUPPORTED_FOR_REGIONS_WITH_GLOBAL_SCOPE_NOT_0
.toLocalizedString(this.scope));
}
if (isLockingSuspendedByCurrentThread()) {
throw new IllegalStateException(
LocalizedStrings.DistributedRegion_THIS_THREAD_HAS_SUSPENDED_ALL_LOCKING_FOR_THIS_REGION
.toLocalizedString());
}
return new DistributedLock(key);
}
示例10: getTickets
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
@Override
public Collection<Ticket> getTickets() {
final Collection<Ticket> collection = new HashSet<>();
final Lock lock = this.hz.getLock(getClass().getName());
lock.lock();
try {
final PagingPredicate pagingPredicate = new PagingPredicate(this.pageSize);
for (Collection<Ticket> entrySet = this.registry.values(pagingPredicate);
!entrySet.isEmpty();
pagingPredicate.nextPage(), entrySet = this.registry.values(pagingPredicate)) {
for (final Ticket entry : entrySet) {
collection.add(decodeTicket(entry));
}
}
} finally {
lock.unlock();
}
return collection;
}
示例11: testAsReadLock
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* asReadLock can be locked and unlocked
*/
public void testAsReadLock() throws Throwable {
StampedLock sl = new StampedLock();
Lock lock = sl.asReadLock();
for (Action locker : lockLockers(lock)) {
locker.run();
assertTrue(sl.isReadLocked());
assertFalse(sl.isWriteLocked());
assertEquals(1, sl.getReadLockCount());
locker.run();
assertTrue(sl.isReadLocked());
assertEquals(2, sl.getReadLockCount());
lock.unlock();
lock.unlock();
assertUnlocked(sl);
}
}
示例12: getChangesToBest
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
@Override
public Vector getChangesToBest() {
Vector ret = new Vector();
Lock lock = currentSolution().getLock().readLock();
lock.lock();
try {
for (Lecture lecture: currentSolution().getModel().variables()) {
Placement placement = currentSolution().getAssignment().getValue(lecture);
if (!ToolBox.equals(lecture.getBestAssignment(), placement)) {
RecordedAssignment a = new RecordedAssignment(this,(Placement)lecture.getBestAssignment(),placement);
if (lecture.getBestAssignment()!=null) {
a.getBefore().setDetails(new ClassAssignmentDetails(this,lecture,(Placement)lecture.getBestAssignment(),false));
}
if (placement!=null) {
a.getAfter().setDetails(new ClassAssignmentDetails(this,lecture,false));
}
ret.addElement(a);
}
}
} finally {
lock.unlock();
}
return ret;
}
示例13: create
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
/**
* Creates a cleaner task based on the configuration. This is provided for
* convenience.
*
* @param conf
* @param store
* @param metrics
* @param cleanerTaskLock lock that ensures a serial execution of cleaner
* task
* @return an instance of a CleanerTask
*/
public static CleanerTask create(Configuration conf, SCMStore store,
CleanerMetrics metrics, Lock cleanerTaskLock) {
try {
// get the root directory for the shared cache
String location =
conf.get(YarnConfiguration.SHARED_CACHE_ROOT,
YarnConfiguration.DEFAULT_SHARED_CACHE_ROOT);
long sleepTime =
conf.getLong(YarnConfiguration.SCM_CLEANER_RESOURCE_SLEEP_MS,
YarnConfiguration.DEFAULT_SCM_CLEANER_RESOURCE_SLEEP_MS);
int nestedLevel = SharedCacheUtil.getCacheDepth(conf);
FileSystem fs = FileSystem.get(conf);
return new CleanerTask(location, sleepTime, nestedLevel, fs, store,
metrics, cleanerTaskLock);
} catch (IOException e) {
LOG.error("Unable to obtain the filesystem for the cleaner service", e);
throw new ExceptionInInitializerError(e);
}
}
示例14: action
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
public final void action(final MapleClient c, final byte mode, final byte type, final int selection) {
if (mode != -1) {
final NPCConversationManager cm = cms.get(c);
if (cm == null || cm.getLastMsg() > -1) {
return;
}
final Lock lock = c.getNPCLock();
lock.lock();
try {
if (cm.pendingDisposal) {
dispose(c);
} else {
c.setClickedNPC();
cm.getIv().invokeFunction("action", mode, type, selection);
}
} catch (final ScriptException | NoSuchMethodException e) {
System.err.println("Error executing NPC script. NPC ID : " + cm.getNpc() + ":" + e);
dispose(c);
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
示例15: getAssignmentInfo
import java.util.concurrent.locks.Lock; //导入依赖的package包/类
@Override
public AssignmentPreferenceInfo getAssignmentInfo(Long classId) {
Lock lock = currentSolution().getLock().readLock();
lock.lock();
try {
Lecture lecture = null;
for (Lecture l: currentSolution().getModel().variables()) {
if (l.getClassId().equals(classId)) {
lecture = l; break;
}
}
if (lecture==null) return null;
Placement placement = (Placement)currentSolution().getAssignment().getValue(lecture);
if (placement==null) return null;
return new AssignmentPreferenceInfo(this,placement);
} finally {
lock.unlock();
}
}