Java Code Examples for java.util.concurrent.locks.Lock
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/net/.
Source file: MysqlServerConnection.java

public void finishedCommand(CommandInfo command){ if (commandRunner != null) { final Lock lock=commandRunner.getLock(); lock.lock(); try { commandRunner.setRunnerStatus(CommandMessageQueueRunner.RunnerStatus.WAITTOEND); this.commandInfo=null; } finally { lock.unlock(); } } }
Example 2
From project bitcask-java, under directory /src/main/java/com/trifork/bitcask/.
Source file: BitCaskKeyDir.java

public BitCaskEntry get(ByteString key){ Lock readLock=rwl.readLock(); readLock.lock(); try { return map.get(key); } finally { readLock.unlock(); } }
Example 3
/** * Reentrant ???? */ public void testLockJDK5(){ Lock lock=new ReentrantLock(); lock.lock(); try { ticket--; System.out.println("The ticket: " + ticket); } finally { lock.unlock(); } }
Example 4
From project giraph, under directory /src/main/java/org/apache/giraph/graph/partition/.
Source file: DiskBackedPartitionStore.java

/** * Create a new lock for a partition, lock it, and return it. If already existing, return null. * @param partitionId Partition id * @return A newly created lock, or null if already present */ private Lock createLock(Integer partitionId){ Lock lock=new ReentrantLock(true); lock.lock(); if (partitionLocks.putIfAbsent(partitionId,lock) != null) { return null; } return lock; }
Example 5
From project grails-data-mapping, under directory /grails-datastore-gemfire/src/main/groovy/org/grails/datastore/mapping/gemfire/engine/.
Source file: GemfireEntityPersister.java

@Override public Object lock(final Serializable id) throws CannotAcquireLockException { final GemfireTemplate template=gemfireDatastore.getTemplate(getPersistentEntity()); return template.execute(new GemfireCallback(){ public Object doInGemfire( Region region) throws GemFireCheckedException, GemFireException { final Lock lock=region.getDistributedLock(id); lock.lock(); final Object o=region.get(id); distributedLocksHeld.put(o,lock); return o; } } ); }
Example 6
From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/lock/distributed/.
Source file: MemberAcquireLockCommand.java

/** * {@inheritDoc} * @see net.sf.hajdbc.distributed.Command#execute(java.lang.Object) */ @Override public Boolean execute(LockCommandContext context){ Lock lock=context.getLock(this.descriptor); boolean locked=lock.tryLock(); if (locked) { Map<LockDescriptor,Lock> lockMap=context.getRemoteLocks(this.descriptor); synchronized (lockMap) { lockMap.put(this.descriptor,lock); } } return locked; }
Example 7
From project hawtjournal, under directory /src/main/java/org/fusesource/hawtjournal/api/.
Source file: DataFileAccessor.java

private Lock getOrCreateLock(Thread thread,Integer file){ ConcurrentMap<Integer,Lock> locks=perThreadDataFileLocks.get(thread); if (locks == null) { locks=new ConcurrentHashMap<Integer,Lock>(); perThreadDataFileLocks.put(thread,locks); } Lock lock=locks.get(file); if (lock == null) { lock=new ReentrantLock(); locks.put(file,lock); } return lock; }
Example 8
From project hibernate-dsc, under directory /src/main/java/com/corundumstudio/concurrent/.
Source file: CompositeLock.java

@Override public boolean tryLock(){ ListIterator<ReentrantLock> listIterator=locks.listIterator(); while (listIterator.hasNext()) { Lock lock=listIterator.next(); if (!lock.tryLock()) { unlockAcuriedLocks(listIterator); return false; } } return true; }
Example 9
From project james-mailbox, under directory /store/src/main/java/org/apache/james/mailbox/store/.
Source file: JVMMailboxPathLocker.java

private Lock getLock(ReadWriteLock lock,boolean writeLock){ Lock l; if (writeLock) { l=lock.writeLock(); } else { l=lock.readLock(); } return l; }
Example 10
From project Journal.IO, under directory /src/main/java/journal/io/api/.
Source file: DataFileAccessor.java

private Lock getOrCreateLock(Thread thread,Integer file){ ConcurrentMap<Integer,Lock> locks=perThreadDataFileLocks.get(thread); if (locks == null) { locks=new ConcurrentHashMap<Integer,Lock>(); perThreadDataFileLocks.put(thread,locks); } Lock lock=locks.get(file); if (lock == null) { lock=new ReentrantLock(); locks.put(file,lock); } return lock; }
Example 11
@Override public void illuminate(){ final Lock lock=getLock(); try { lock.lock(); super.illuminate(); } finally { lock.unlock(); } }
Example 12
From project logback, under directory /logback-core/src/test/java/ch/qos/logback/core/issue/.
Source file: LBCORE97.java

public static void usingUnfairLock(int threadCount) throws InterruptedException { Lock lock=new ReentrantLock(); Runnable[] runnables=new Runnable[threadCount]; Thread[] threads=new Thread[threadCount]; for (int i=0; i < threadCount; i++) { runnables[i]=new LockRunnable(lock); threads[i]=new Thread(runnables[i]); } String text="usingUnfairLock"; execute(text,threads); print(text,runnables); }
Example 13
From project maven3-support, under directory /maven3-plugin/src/main/java/org/hudsonci/maven/plugin/dependencymonitor/internal/.
Source file: ProjectArtifactCacheImpl.java

public ArtifactsPair getArtifacts(final AbstractProject project){ checkNotNull(project); Lock lock=readLock(); try { return new ArtifactsPair(getProducedArtifacts(project),getConsumedArtifacts(project)); } finally { lock.unlock(); } }
Example 14
From project menagerie, under directory /src/main/java/org/menagerie/collections/.
Source file: ZkReadWriteIterator.java

@Override public boolean hasNext(){ Lock readLock=safety.readLock(); readLock.lock(); try { return super.hasNext(); } finally { readLock.unlock(); } }
Example 15
From project moho, under directory /moho-remote/src/main/java/com/voxeo/rayo/client/.
Source file: RayoClient.java

/** * Adds a callback class to listen for events on all the incoming stanzas. * @param listener Stanza Callback. */ public void addStanzaListener(StanzaListener listener){ Lock lock=connectionLock.readLock(); lock.lock(); try { connection.addStanzaListener(listener); } finally { lock.unlock(); } }
Example 16
From project ps3mediaserver, under directory /src/main/java/net/pms/util/.
Source file: TaskRunner.java

protected Lock getLock(String name){ synchronized (uniquenessLock) { Lock lk=uniquenessLock.get(name); if (lk == null) { lk=new ReentrantLock(); uniquenessLock.put(name,lk); } return lk; } }
Example 17
From project qi4j-core, under directory /io/src/test/java/org/qi4j/io/.
Source file: InputOutputTest.java

@Test public void testLock() throws IOException { Lock inputLock=new ReentrantLock(); Lock outputLock=new ReentrantLock(); URL source=getClass().getResource("/iotest.txt"); File destination=File.createTempFile("test",".txt"); destination.deleteOnExit(); lock(inputLock,text(source)).transferTo(lock(outputLock,Outputs.text(destination))); }
Example 18
From project clustermeister, under directory /provisioning/src/test/java/com/github/nethad/clustermeister/provisioning/jppf/.
Source file: PublicIpIntegrationTest.java

@Test public void testDriverBlockingUntilPublicIpAvailable() throws InterruptedException { final Lock lock=new ReentrantLock(); final Condition condition=lock.newCondition(); final AtomicBoolean isBlocking=new AtomicBoolean(false); final JPPFLocalDriver driver=new JPPFLocalDriver(null); new Thread(new Runnable(){ @Override public void run(){ lock.lock(); try { isBlocking.set(true); condition.signal(); } finally { lock.unlock(); } driver.getIpAddress(); } } ).start(); lock.lock(); try { while (!isBlocking.get()) { condition.await(); Thread.sleep(100); } } finally { lock.unlock(); } nodeDeployer.addListener(driver); assertThat(driver.getIpAddress(),is("1.2.3.5")); }
Example 19
From project DirectMemory, under directory /integrations/ehcache/src/main/java/org/apache/directmemory/ehcache/.
Source file: DirectMemoryStore.java

@Override public Element removeElement(Element element,ElementValueComparator comparator) throws NullPointerException { if (element == null || element.getObjectKey() == null) { return null; } Pointer<Element> pointer=directMemoryCache.getPointer(element.getObjectKey()); if (pointer == null) { return null; } Lock lock=bufferLocks.get(pointer.getBufferNumber()); lock.lock(); try { Element toRemove=directMemoryCache.retrieve(element.getObjectKey()); if (comparator.equals(element,toRemove)) { directMemoryCache.free(element.getObjectKey()); return toRemove; } else { return null; } } finally { lock.unlock(); } }
Example 20
From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/conn/tsccm/.
Source file: TestSpuriousWakeup.java

@Test public void testSpuriousWakeup() throws Exception { SchemeRegistry schreg=new SchemeRegistry(); SchemeSocketFactory sf=PlainSocketFactory.getSocketFactory(); schreg.register(new Scheme("http",80,sf)); XTSCCM mgr=new XTSCCM(schreg); try { mgr.setMaxTotal(1); mgr.setDefaultMaxPerRoute(1); ClientConnectionRequest connRequest=mgr.requestConnection(ROUTE,null); ManagedClientConnection conn=connRequest.getConnection(0,null); Assert.assertNotNull(conn); GetConnThread gct=new GetConnThread(mgr,ROUTE,0L); gct.start(); Thread.sleep(100); Assert.assertEquals("thread not waiting",Thread.State.WAITING,gct.getState()); Lock lck=mgr.extendedCPBR.getLock(); Condition cnd=mgr.extendedCPBR.newestWT.getCondition(); for (int i=0; i < 3; i++) { if (i > 0) Thread.sleep(333); try { lck.lock(); cnd.signalAll(); } finally { lck.unlock(); } Thread.sleep(100); Assert.assertEquals("thread no longer waiting, iteration " + i,Thread.State.WAITING,gct.getState()); } } finally { mgr.shutdown(); } }
Example 21
From project jax-rs-hateoas, under directory /jax-rs-hateoas-core/src/main/java/com/jayway/jaxrs/hateoas/.
Source file: DefaultHateoasContext.java

/** * Checks if the specified class has been registered. If not add the class to the set mapping registred classes. * @param clazz the class to check * @return <code>true</code> if the class has already been registered,<code>false</code> otherwise. */ public boolean isInitialized(Class<?> clazz){ Lock readLock=LOCK.readLock(); try { readLock.lock(); if (initializedClasses.contains(clazz)) { return true; } } finally { readLock.unlock(); } Lock writeLock=LOCK.writeLock(); try { writeLock.lock(); if (!initializedClasses.contains(clazz)) { initializedClasses.add(clazz); return false; } } finally { writeLock.unlock(); } return true; }
Example 22
/** * Helper method to 'simulate' the methods of an entry set of the btree. */ protected static boolean containsValue(Object value,BTree btree) throws IOException { Lock readLock=btree.getLock().readLock(); try { readLock.lock(); BTree.BTreeTupleBrowser browser=btree.browse(); BTree.BTreeTuple tuple=new BTree.BTreeTuple(); while (browser.getNext(tuple)) { if (tuple.value.equals(value)) return (true); } } finally { readLock.unlock(); } return (false); }
Example 23
From project magrit, under directory /server/core/src/main/java/org/kercoin/magrit/core/build/pipeline/.
Source file: PipelineImpl.java

@Override public V call() throws Exception { Lock lock=t.getUnderlyingResource().getLock(); try { lock.lockInterruptibly(); Key k=t.getKey(); boolean hasAcquired=false; try { do { hasAcquired=slots.tryAcquire(WORKER_TIMER_SECONDS,TimeUnit.SECONDS); } while (!hasAcquired); main.writeLock().lockInterruptibly(); workings.add(k); main.writeLock().unlock(); notifier.justStarted(k); return t.call(); } finally { if (hasAcquired) { if (!main.writeLock().isHeldByCurrentThread()) { main.writeLock().lockInterruptibly(); } tasks.remove(k); workings.remove(k); main.writeLock().unlock(); slots.release(); notifier.justEnded(k); } } } finally { lock.unlock(); } }
Example 24
From project moji, under directory /src/main/java/fm/last/moji/impl/.
Source file: MojiFileImpl.java

@Override public InputStream getInputStream() throws IOException { log.debug("getInputStream() : {}",this); InputStream inputStream=null; try { Lock readLock=lock.readLock(); readLock.lock(); GetInputStreamCommand command=new GetInputStreamCommand(key,domain,httpFactory,readLock); executor.executeCommand(command); inputStream=command.getInputStream(); log.debug("getInputStream() -> {}",inputStream); } catch ( Throwable e) { unlockQuietly(lock.readLock()); IOUtils.closeQuietly(inputStream); if (e instanceof IOException) { throw (IOException)e; } else { throw new RuntimeException(e); } } return inputStream; }
Example 25
From project nuxeo-services, under directory /nuxeo-platform-web-common/src/main/java/org/nuxeo/ecm/platform/web/common/requestcontroller/filter/.
Source file: NuxeoRequestControllerFilter.java

/** * Releases the {@link Lock} if present in the HttpSession. */ public static boolean simpleReleaseSyncOnSession(HttpServletRequest request){ HttpSession session=request.getSession(false); if (session == null) { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request,"No more HttpSession: can not unlock !, HttpSession must have been invalidated")); } return false; } log.debug("Trying to unlock on session " + session.getId() + " on Thread "+ Thread.currentThread().getId()); Lock lock=(Lock)session.getAttribute(SESSION_LOCK_KEY); if (lock == null) { log.error("Unable to find session lock, HttpSession may have been invalidated"); return false; } else { try { lock.unlock(); } catch ( Throwable t) { log.debug("Unlock failed on request " + request.getRequestURI()); return false; } if (request.getAttribute(SYNCED_REQUEST_FLAG) != null) { request.removeAttribute(SYNCED_REQUEST_FLAG); } if (log.isDebugEnabled()) { log.debug("session unlocked on Thread "); } return true; } }
Example 26
From project Pinkie, under directory /src/main/java/com/hellblazer/pinkie/.
Source file: ChannelHandler.java

/** * Close the open handlers managed by the receiver */ public void closeOpenHandlers(){ final Lock myLock=handlersLock; myLock.lock(); try { SocketChannelHandler handler=openHandlers; while (handler != null) { handler.close(); handler=handler.next(); } openHandlers=null; } finally { myLock.unlock(); } }
Example 27
From project qi4j-libraries, under directory /locking/src/main/java/org/qi4j/library/locking/.
Source file: ReadLockConcern.java

public Object invoke(Object o,Method method,Object[] objects) throws Throwable { Lock readLock=lock.readLock(); lock(readLock); try { return next.invoke(o,method,objects); } finally { try { lock.readLock().unlock(); } catch ( Exception e) { e.printStackTrace(); } } }
Example 28
From project collector, under directory /src/test/java/com/ning/metrics/collector/realtime/.
Source file: RealTimeQueueTestModule.java

@Override protected void configure(){ bind(Lock.class).annotatedWith(Names.named("amqSessionLock")).toInstance(sessionLock); bind(Collection.class).annotatedWith(Names.named("sentEvents")).toInstance(sentEvents); bind(GlobalEventQueueStats.class).asEagerSingleton(); ConfigurationObjectFactory configFactory=new CollectorConfigurationObjectFactory(System.getProperties()); bind(ConfigurationObjectFactory.class).toInstance(configFactory); final EventQueueConnectionFactory factory=new EventQueueConnectionFactory(){ @Override public EventQueueConnection createConnection(){ return new TestEventQueueConnection(); } } ; bind(EventQueueConnectionFactory.class).toInstance(factory); bind(EventQueueProcessor.class).to(EventQueueProcessorImpl.class).asEagerSingleton(); }
Example 29
From project DeuceSTM, under directory /src/test/org/deuce/benchmark/stmbench7/locking/.
Source file: MGLockingOperationExecutor.java

public int execute() throws OperationFailedException { try { for ( Lock lock : locksToAcquire) lock.lock(); return op.performOperation(); } finally { if (Parameters.sequentialReplayEnabled) lastOperationTimestamp=globalCounter.getAndIncrement(); AssemblyLocksAcquired threadAssemblyLocksAcquired=assemblyLocksAcquired.get(); for (int level=1; level <= Parameters.NumAssmLevels; level++) { if (threadAssemblyLocksAcquired.isReadAcquired[level]) assemblyReadLocks[level].unlock(); if (threadAssemblyLocksAcquired.isWriteAcquired[level]) assemblyWriteLocks[level].unlock(); } threadAssemblyLocksAcquired.clear(); for ( Lock lock : locksToAcquire) lock.unlock(); } }
Example 30
From project erjang, under directory /src/main/java/erjang/driver/.
Source file: EDriverInstance.java

/** * @return */ protected Lock driver_pdl_create(){ if (pdl == null) { pdl=new ReentrantLock(); } return pdl; }
Example 31
From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/model/.
Source file: PageViewWindow.java

PageViewWindow(int index,int pageNumber,Lock preloadingLock,ContentRepo repo,PageActivity.WeiboPageViewFactory pageViewFactory,ExecutorService executor,ThumbnailViewContainer previousPeiboPageViewContainer){ super(index,pageNumber,preloadingLock); this.executor=executor; this.repo=repo; this.pageViewFactory=pageViewFactory; this.previousPeiboPageViewContainer=previousPeiboPageViewContainer; startTask(); mainLooper=null; }
Example 32
From project flume, under directory /flume-ng-sinks/flume-ng-hbase-sink/src/main/java/org/apache/flume/sink/hbase/.
Source file: AsyncHBaseSink.java

public FailureCallback(Lock lck,AtomicInteger callbacksReceived,AtomicBoolean txnFail,Condition condition){ this.lock=lck; this.callbacksReceived=callbacksReceived; this.txnFail=txnFail; this.condition=condition; }
Example 33
From project hibernate-ogm, under directory /hibernate-ogm-core/src/main/java/org/hibernate/ogm/datastore/map/impl/.
Source file: MapDatastoreProvider.java

private void acquireLock(EntityKey key,int timeout,Lock writeLock){ try { if (timeout == -1) { writeLock.lockInterruptibly(); } else if (timeout == 0) { boolean locked=writeLock.tryLock(); if (!locked) { throw new PessimisticLockException("lock on key " + key + " was not available"); } } else { writeLock.tryLock(timeout,TimeUnit.MILLISECONDS); } } catch ( InterruptedException e) { throw new PessimisticLockException("timed out waiting for lock on key " + key,e); } acquiredLocksPerThread.get().add(writeLock); }
Example 34
From project httpcore, under directory /httpcore/src/main/java/org/apache/http/pool/.
Source file: PoolEntryFuture.java

PoolEntryFuture(final Lock lock,final FutureCallback<T> callback){ super(); this.lock=lock; this.condition=lock.newCondition(); this.callback=callback; }
Example 35
From project jagger, under directory /chassis/coordinator.zookeeper/src/main/java/com/griddynamics/jagger/coordinator/zookeeper/.
Source file: ZookeeperCoordinator.java

private StatusWatcher(ZNode node,Lock lock,Collection<NodeId> currentIds,StatusChangeListener statusChangeListener){ this.node=node; this.lock=lock; this.currentIds=currentIds; this.statusChangeListener=statusChangeListener; }
Example 36
From project openfire-jboss-clustering, under directory /src/main/java/com/enernoc/rnd/openfire/cluster/cache/.
Source file: ClusteredCacheFactory.java

@SuppressWarnings("unchecked") public Lock getLock(Object key,Cache cache){ if (cache instanceof CacheWrapper) cache=((CacheWrapper)cache).getWrappedCache(); if (!(cache instanceof JBossCache)) cache=this.createCache(cache.getName()); log.debug("Creating lock for {} on cache {}",key,cache.getName()); return ((JBossCache)cache).getLock(key); }
Example 37
From project Possom, under directory /war/src/main/java/no/sesat/search/http/filters/.
Source file: SiteLocatorFilter.java

private static long tryLock(final HttpServletRequest request,final Deque<ServletRequest> deque,final Lock lock,long timeLeft){ final long start=System.currentTimeMillis(); try { do { timeLeft=WAIT_TIME - (System.currentTimeMillis() - start); if (0 >= timeLeft || !lock.tryLock(timeLeft,TimeUnit.MILLISECONDS)) { break; } else if (deque.peek() != request) { lock.unlock(); } } while (deque.peek() != request); } catch ( InterruptedException ie) { LOG.error("Failed using user's lock",ie); } return timeLeft; }
Example 38
From project rave, under directory /rave-components/rave-commons/src/main/java/org/apache/rave/service/impl/.
Source file: DefaultLockService.java

@Override public synchronized Lock borrowLock(String key){ logger.debug("BorrowLock called with key [{}]",key); ReferenceTrackingLock lock=locks.get(key); if (lock == null) { logger.debug("Existing lock not found under key [{}] - creating new lock",key); lock=new ReferenceTrackingLock(key); locks.put(key,lock); } else { logger.debug("Existing lock found under key [{}] - returning existing lock",key); } lock.incrementReferenceCount(); logger.debug("Returning lock with key [{}] - and referenceCount [{}]",lock.getKey(),lock.getReferenceCount()); return lock; }