Java Code Examples for java.util.concurrent.locks.ReentrantLock
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 amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.
Source file: TaskControl.java

@SuppressWarnings("unchecked") public TaskControl(Comparator<PrioritizedTask> activeComparator,int maxThreads,ThreadFactory threadFactory,Log log){ this.log=log; ApplicationIllegalArgumentException.notNull(activeComparator,"activeComparator"); this.eligibleTasks=new PriorityBlockingQueue<PrioritizedTask>(20,activeComparator); this.stateChangeNotificator=new ReentrantLock(); this.newTasks=this.stateChangeNotificator.newCondition(); this.runningTasks=new AtomicInteger(0); this.threadFactory=threadFactory; int keepAliveTime=10; int corePoolSize=1; this.executor=new ThreadPoolExecutor(corePoolSize,Math.max(corePoolSize,maxThreads),keepAliveTime,MICROSECONDS,(BlockingQueue)this.eligibleTasks,threadFactory); this.stayActive=true; }
Example 2
From project cleo, under directory /src/main/java/cleo/search/store/.
Source file: KratiBufferedInts.java

@Override public boolean delete(String key,long scn) throws Exception { ReentrantLock l=getLock(key); l.lock(); try { int index=getExtensionIndex(key); if (index >= 0) { extInts.set(index,null,scn); } return bufInts.delete(key,scn); } finally { l.unlock(); } }
Example 3
From project core_4, under directory /impl/src/main/java/org/richfaces/application/push/impl/.
Source file: SessionQueue.java

public void remove(Session session){ final ReentrantLock lock=this.lock; lock.lock(); checkActiveState(); try { queue.remove(session); } finally { lock.unlock(); } }
Example 4
From project hibernate-dsc, under directory /src/main/java/com/corundumstudio/concurrent/.
Source file: ConcurrentWeakLockMap.java

public ReentrantLock getLock(K key){ ReentrantLock lock=lockMap.get(key); if (lock == null) { ReentrantLock newlock=new ReentrantLock(); lock=lockMap.putIfAbsent(key,newlock); if (lock == null) { lock=newlock; } } return lock; }
Example 5
From project Jetwick, under directory /src/main/java/de/jetwick/util/.
Source file: MaxBoundSet.java

public boolean contains(T t){ final ReentrantLock lock=this.lock; lock.lock(); try { long now=System.currentTimeMillis(); Long lastTime=objMap.get(t); if (lastTime != null && now - lastTime <= maxAge) return true; else return false; } finally { lock.unlock(); } }
Example 6
From project usergrid-stack, under directory /core/src/main/java/org/usergrid/locking/singlenode/.
Source file: SingleNodeLockManagerImpl.java

public ReentrantLock getCreateLockInternal(String lockPath){ ReentrantLock lock=localLocks.get().get(lockPath); if (lock != null) { return lock; } synchronized (this) { lock=globalLocks.get(lockPath); if (lock == null) { lock=new ReentrantLock(); globalLocks.put(lockPath,lock); } } return lock; }
Example 7
From project WaarpR66, under directory /src/main/java/org/waarp/openr66/protocol/networkhandler/.
Source file: NetworkTransaction.java

/** * @param address * @return True if this channel is currently in shutdown */ public static boolean isShuttingdownNetworkChannel(SocketAddress address){ ReentrantLock socketLock=getChannelLock(address); socketLock.lock(); try { return !isAddressValid(address); } finally { socketLock.unlock(); } }
Example 8
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/client/methods/.
Source file: HttpRequestBase.java

@Override public Object clone() throws CloneNotSupportedException { HttpRequestBase clone=(HttpRequestBase)super.clone(); clone.abortLock=new ReentrantLock(); clone.aborted=false; clone.releaseTrigger=null; clone.connRequest=null; clone.headergroup=(HeaderGroup)CloneUtils.clone(this.headergroup); clone.params=(HttpParams)CloneUtils.clone(this.params); return clone; }
Example 9
From project archaius, under directory /archaius-core/src/main/java/com/netflix/config/.
Source file: ConcurrentMapConfiguration.java

/** * Create an instance with an empty map. */ public ConcurrentMapConfiguration(){ map=new ConcurrentHashMap<String,Object>(); for (int i=0; i < NUM_LOCKS; i++) { locks[i]=new ReentrantLock(); } }
Example 10
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.
Source file: BlockingStack.java

/** * Add an object to the stack and signal * @param object Object to add * @throws InterruptedException */ void push(T object) throws InterruptedException { final ReentrantLock pushLock=this.mPushLock; int origSize; pushLock.lockInterruptibly(); try { synchronized (mStack) { origSize=mStack.size(); mStack.push(object); } } finally { pushLock.unlock(); } if (origSize == 0) { final ReentrantLock popLock=mPopLock; popLock.lock(); try { mNotEmpty.signal(); } finally { popLock.unlock(); } } }
Example 11
From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.
Source file: ClientMessageHandler.java

ClientMessageHandler(final ExecutorService callbackService){ Preconditions.checkNotNull(callbackService,"ExecutorService cannot be null"); activeChannel=new AtomicReference<Channel>(null); this.callbackService=callbackService; subscribers=new ConcurrentHashMap<String,Collection<PubSubClient.MessageCallback>>(); lock=new ReentrantLock(); }
Example 12
From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/http/.
Source file: BucketsStreamingHandler.java

public BucketsStreamingHandler(HarakiriMonitor monitor,Bucket bucket,OutputStream output){ this.output=output; this.bucket=bucket; this.monitor=monitor; this.completed=new CountDownLatch(1); updateHandlerLock=new ReentrantLock(); }
Example 13
/** * Reentrant ???? */ public void testLockJDK5(){ Lock lock=new ReentrantLock(); lock.lock(); try { ticket--; System.out.println("The ticket: " + ticket); } finally { lock.unlock(); } }
Example 14
From project flexmojos, under directory /flexmojos-testing/flexmojos-tester/src/main/java/net/flexmojos/oss/test/.
Source file: AbstractControlledThread.java

public void lock(){ if (lock != null) { return; } lock=new ReentrantLock(); lock.lock(); }
Example 15
From project gatein-common, under directory /logging/src/test/java/org/gatein/common/logging/.
Source file: LogTestCase.java

public void testConcurrentGetRace() throws Exception { final ReentrantLock lock=LoggerFactoryImpl.getLock(); lock.lock(); final AtomicReference<Logger> loggerRef=new AtomicReference<Logger>(); final AtomicBoolean done=new AtomicBoolean(); Thread t=new Thread(){ public void run(){ Logger logger=LoggerFactory.getLogger("testConcurrentGetRace"); loggerRef.set(logger); done.set(true); } } ; t.start(); while (!lock.hasQueuedThread(t)) { Thread.sleep(1); } assertEquals(null,LoggerFactoryImpl.peekLogger("testConcurrentGetRace")); Logger logger=LoggerFactory.getLogger("testConcurrentGetRace"); assertNotNull(logger); lock.unlock(); while (!done.get()) { Thread.sleep(1); } assertSame(logger,loggerRef.get()); }
Example 16
From project genobyte, under directory /genobyte/src/main/java/org/obiba/bitwise/.
Source file: BitwiseStoreUtil.java

/** * Locks a <tt>BitwiseStore</tt> to prevent it from being accessed in the middle of a <tt>Runnable</tt> operation. * @param name the name of the store on which to put the lock. * @param r the code segment to execute in lock mode. */ public void lock(String name,Runnable r){ synchronized (MUTEX) { BitwiseStoreRef ref=STORE_MAP.get(name); storeLocks.putIfAbsent(name,new ReentrantLock()); ReentrantLock storeLock=storeLocks.get(name); while ((storeLock.isLocked() && storeLock.isHeldByCurrentThread() == false) || (ref != null && ref.isThreadExclusive() == false)) { if (log.isDebugEnabled()) { Object args[]=new Object[]{storeLock.isLocked(),storeLock.isHeldByCurrentThread(),ref != null,ref.isThreadExclusive()}; log.debug("Waiting for lock: (isLocked [{}] && isHeldByCurrentThread() [{}]) or (ref != null [{}] && isThreadExclusive [{}])",args); } try { ref=null; MUTEX.wait(10 * 1000); } catch ( InterruptedException e) { throw new RuntimeException(e); } ref=STORE_MAP.get(name); } storeLock.lock(); log.debug("Thread [{}] is holding [{}] lock(s) on store [{}]",new Object[]{Thread.currentThread().getId(),storeLock.getHoldCount(),name}); } try { r.run(); } finally { synchronized (MUTEX) { storeLocks.get(name).unlock(); MUTEX.notify(); } } }
Example 17
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 18
From project graph-collections, under directory /src/test/java/org/neo4j/collections/list/.
Source file: TestUnrolledLinkedListConcurrency.java

public StateSynchronizer(Class<? extends Enum> states){ lock=new ReentrantLock(); conditions=new HashMap<Enum,Condition>(); for ( Enum state : states.getEnumConstants()) { conditions.put(state,lock.newCondition()); } }
Example 19
From project gs-core, under directory /src/org/graphstream/graph/implementations/.
Source file: Graphs.java

SynchronizedGraph(Graph g){ super(g); elementLock=new ReentrantLock(); synchronizedNodes=new HashMap<String,Node>(); synchronizedEdges=new HashMap<String,Edge>(); for ( Node n : g.getEachNode()) synchronizedNodes.put(n.getId(),new SynchronizedNode(this,n)); for ( Edge e : g.getEachEdge()) synchronizedEdges.put(e.getId(),new SynchronizedEdge(this,e)); }
Example 20
From project harmony, under directory /harmony.idb/src/main/java/org/opennaas/extensions/idb/notification/producer/.
Source file: NotificationSenderMonitor.java

/** * Constructor for the notification monitor. * @param timeout in sec */ public NotificationSenderMonitor(final int timeout){ this.timeout=timeout * 1000; this.senderList=new ArrayList<NotificationSender>(); this.lock=new ReentrantLock(); this.pause=this.lock.newCondition(); this.maxSendTrials=Config.getInt("idb","maxNotificationRetries").intValue(); this.sendTrials=1; }
Example 21
From project hawtdispatch, under directory /hawtdispatch/src/test/java/org/fusesource/hawtdispatch/internal/pool/.
Source file: StealingPool.java

/** * Creates a {@code ForkJoinPool} with the given parallelism . * @param parallelism the parallelism level * @throws IllegalArgumentException if parallelism less than orequal to zero, or greater than implementation limit */ public StealingPool(String name,int parallelism,int priority){ if (parallelism <= 0 || parallelism > MAX_THREADS) throw new IllegalArgumentException(); this.name=name; this.parallelism=parallelism; this.priority=priority; this.workerLock=new ReentrantLock(); this.termination=workerLock.newCondition(); this.stealCount=new AtomicLong(); this.submissionQueue=new LinkedTransferQueue<Task>(); threads=new StealingThread[parallelism]; for (int i=0; i < parallelism; ++i) { threads[i]=createWorker(i); } }
Example 22
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 23
From project httpClient, under directory /httpclient/src/main/java/org/apache/http/client/methods/.
Source file: HttpRequestBase.java

@Override public Object clone() throws CloneNotSupportedException { HttpRequestBase clone=(HttpRequestBase)super.clone(); clone.abortLock=new ReentrantLock(); clone.aborted=false; clone.cancellable=null; clone.headergroup=CloneUtils.cloneObject(this.headergroup); clone.params=CloneUtils.cloneObject(this.params); return clone; }
Example 24
From project httpcore, under directory /httpcore/src/main/java/org/apache/http/pool/.
Source file: AbstractConnPool.java

public AbstractConnPool(final ConnFactory<T,C> connFactory,int defaultMaxPerRoute,int maxTotal){ super(); this.connFactory=Args.notNull(connFactory,"Connection factory"); this.defaultMaxPerRoute=Args.notNegative(defaultMaxPerRoute,"Max per route value"); this.maxTotal=Args.notNegative(maxTotal,"Max total value"); this.lock=new ReentrantLock(); this.routeToPool=new HashMap<T,RouteSpecificPool<T,C,E>>(); this.leased=new HashSet<E>(); this.available=new LinkedList<E>(); this.pending=new LinkedList<PoolEntryFuture<E>>(); this.maxPerRoute=new HashMap<T,Integer>(); }
Example 25
From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/topology/.
Source file: ClusterFromZK.java

/** * any topology */ public ClusterFromZK(String clusterName,ZkClient zkClient,String machineId){ this.zkClient=zkClient; this.taskPath="/s4/clusters/" + clusterName + "/tasks"; this.processPath="/s4/clusters/" + clusterName + "/process"; this.clusterName=clusterName; this.lock=new ReentrantLock(); this.listeners=new ArrayList<ClusterChangeListener>(); this.clusterRef=new AtomicReference<PhysicalCluster>(); zkClient.subscribeChildChanges(taskPath,this); zkClient.subscribeChildChanges(processPath,this); }
Example 26
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 27
From project jpropel-light, under directory /src/propel/core/collections/buffers/.
Source file: SharedBuffer.java

/** * Default constructor. * @throws SuperTypeTokenException When called without using anonymous class semantics. */ public SharedBuffer(){ super(); lockObject=new ReentrantLock(); notFull=lockObject.newCondition(); notEmpty=lockObject.newCondition(); }
Example 28
From project jredis, under directory /core/ri/src/main/java/org/jredis/ri/alphazero/connection/.
Source file: SyncConnection.java

/** * This constructor will pass the connection spec to the super class constructor and create and install the {@link Protocol} handler delegate instance for this {@link SyncConnection}. If you definitely need to specify the redis server version, and the protocol implementation for that version exists, you should use this constructor. Otherwise, it is recommended that the {@link SyncConnection#SyncConnection(ConnectionSpec)}be used. <p> This constructor will open the socket connection immediately. * @param connectionSpec * @param redisversion * @throws ClientRuntimeException due to either dns (host connectivity) or any IO issues related to establishing the socket connection to the specified server. * @throws ProviderException if the version specified is not supported. */ public SyncConnection(ConnectionSpec connectionSpec) throws ClientRuntimeException, ProviderException { super(connectionSpec.setModality(Modality.Synchronous)); if (spec.getConnectionFlag(Flag.RELIABLE)) lock=new ReentrantLock(false); else { lock=null; spec.getConnectionFlag(Flag.RELIABLE); } }
Example 29
From project juzu, under directory /core/src/main/java/juzu/impl/inject/spi/cdi/.
Source file: SingletonBean.java

SingletonBean(Class type,Iterable<Annotation> qualifiers,Object instance){ super(type,Scope.SINGLETON,qualifiers); this.instance=instance; this.initialized=false; this.lock=new ReentrantLock(); }
Example 30
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 31
From project menagerie, under directory /src/main/java/org/menagerie/.
Source file: ZkPrimitive.java

/** * Creates a new ZkPrimitive with the correct node information. * @param baseNode the base node to use * @param zkSessionManager the session manager to use * @param privileges the privileges for this node. */ protected ZkPrimitive(String baseNode,ZkSessionManager zkSessionManager,List<ACL> privileges){ if (baseNode == null) throw new NullPointerException("No base node specified!"); this.baseNode=baseNode; this.zkSessionManager=zkSessionManager; this.privileges=privileges; this.localLock=new ReentrantLock(true); condition=this.localLock.newCondition(); signalWatcher=new SignallingWatcher(this); ensureNodeExists(); }
Example 32
From project osgi-utils, under directory /com.c4biz.osgiutils.assertions/src/com/c4biz/osgiutils/assertions/services/.
Source file: ServiceUtils.java

/** * Get ServiceReference by filter with timeout. * @param bc BundleContext * @param filter filter * @param timeout time interval to wait. If zero, the method will wait indefinately. * @param timeUnit time unit for the time interval * @return ServiceReference instance or <code>null</code> * @throws IllegalArgumentException If the value of timeout is negative * @throws NullPointerException If <code>bc</code>, <code>filter</code> or<code>timeUnit</code> are <code>null</code> */ public static ServiceReference<?> getServiceReference(BundleContext bc,Filter filter,long timeout,TimeUnit timeUnit){ final ReentrantLock lock=new ReentrantLock(); long timeoutInMillis=timeUnit.toMillis(timeout); ServiceTracker tracker=new ServiceTracker(bc,filter,new ServiceTrackerCustomizerWithLock(bc,lock)); tracker.open(); try { return waitForServiceReference(tracker,timeoutInMillis,lock); } catch ( InterruptedException e) { return null; } finally { tracker.close(); } }
Example 33
From project platform_external_apache-http, under directory /src/org/apache/http/client/methods/.
Source file: HttpRequestBase.java

@Override public Object clone() throws CloneNotSupportedException { HttpRequestBase clone=(HttpRequestBase)super.clone(); clone.abortLock=new ReentrantLock(); clone.aborted=false; clone.releaseTrigger=null; clone.connRequest=null; clone.headergroup=(HeaderGroup)CloneUtils.clone(this.headergroup); clone.params=(HttpParams)CloneUtils.clone(this.params); return clone; }
Example 34
From project Possom, under directory /war/src/main/java/no/sesat/search/http/filters/.
Source file: SiteLocatorFilter.java

private static void doChainFilter(final FilterChain chain,final HttpServletRequest request,final HttpServletResponse response) throws IOException, ServletException { final HttpSession session=request.getSession(); final Deque<ServletRequest> deque=getUsersDeque(session); final ReentrantLock lock=(ReentrantLock)session.getAttribute(USER_REQUEST_LOCK); long timeLeft=WAIT_TIME; try { if (deque.offerFirst(request)) { timeLeft=tryLock(request,deque,lock,timeLeft); } if (lock.isHeldByCurrentThread()) { chain.doFilter(request,response); } else { if (response instanceof HttpServletResponse) { LOG.warn(" -- response 409 " + (0 < timeLeft ? "(More then " + REQUEST_QUEUE_SIZE + " requests already in queue)" : "(Timeout: Waited " + WAIT_TIME + " ms)")); response.sendError(HttpServletResponse.SC_CONFLICT); } } } finally { deque.remove(request); if (lock.isHeldByCurrentThread()) { lock.unlock(); } } }
Example 35
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 36
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 37
From project rave, under directory /rave-providers/rave-opensocial-provider/rave-opensocial-core/src/test/java/org/apache/rave/opensocial/service/.
Source file: AppDataServiceTest.java

private void testDeletePersonData(String ownerId,String viewerId,Set<String> fieldsToDelete,HashMap<String,String> expectedApplicationDataAfterDelete,ApplicationData applicationData){ UserId userId=new UserId(UserId.Type.userId,VALID_USER_ID); Set<UserId> userIds=new HashSet<UserId>(Arrays.asList(userId)); SecurityToken securityToken=getMockSecurityToken(ownerId,viewerId,VALID_APPLICATION_ID,VALID_MODULE_ID); List<Person> users=Arrays.asList(validPerson); GroupId groupId=new GroupId(GroupId.Type.self,"@self"); expect(personService.getPeople(userIds,groupId,null,securityToken)).andReturn(users); replay(personService); expect(appDataRepository.getApplicationData(VALID_USER_ID,VALID_APPLICATION_ID)).andReturn(applicationData); Capture<ApplicationData> capturedApplicationData=new Capture<ApplicationData>(); expect(appDataRepository.save(capture(capturedApplicationData))).andReturn(null); replay(appDataRepository); ReentrantLock lock=new ReentrantLock(); expect(lockService.borrowLock(anyObject(String.class),anyObject(String.class))).andReturn(lock); lockService.returnLock(lock); replay(lockService); appDataService.deletePersonData(userId,groupId,VALID_APPLICATION_ID,fieldsToDelete,securityToken); ApplicationData expectedApplicationData=new ApplicationDataImpl(applicationData.getId(),applicationData.getUserId(),applicationData.getAppUrl(),expectedApplicationDataAfterDelete); ApplicationData actualApplicationData=capturedApplicationData.getValue(); assertEquals(expectedApplicationData.getId(),actualApplicationData.getId()); assertEquals(expectedApplicationData.getUserId(),actualApplicationData.getUserId()); assertEquals(expectedApplicationData.getAppUrl(),actualApplicationData.getAppUrl()); assertEquals(expectedApplicationData.getData(),actualApplicationData.getData()); }
Example 38
From project repose, under directory /project-set/commons/utilities/src/main/java/com/rackspace/papi/commons/util/pooling/.
Source file: GenericBlockingResourcePool.java

public GenericBlockingResourcePool(ConstructionStrategy<R> constructor,int minPoolSize,int maxPoolSize){ this.constructor=constructor; checkoutCounter=0; pool=new LinkedList<R>(); poolLock=new ReentrantLock(true); poolHasResources=poolLock.newCondition(); resizeMinimum(minPoolSize); resizeMaximum(maxPoolSize); }
Example 39
From project scisoft-core, under directory /uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/.
Source file: HDF5Loader.java

private static void acquireAccess(final String file){ globalLock.lock(); ReentrantLock l; try { l=openFiles.get(file); logger.trace(String.format("Get lock for %s (thd %x)",file,Thread.currentThread().getId())); if (l == null) { l=new ReentrantLock(); logger.trace(" Lock created for {}",file); openFiles.put(file,l); } else { logger.trace(String.format(" Lock exists for %s (%b)",file,l.isLocked())); } } finally { globalLock.unlock(); } if (l.tryLock()) { logger.trace(String.format(" Lock free for %s (or held by current thd %x)",file,Thread.currentThread().getId())); } else { logger.trace(" Wait for held lock for {}",file); l.lock(); logger.trace(String.format(" Hold lock for %s (thd %x)",file,Thread.currentThread().getId())); } }
Example 40
From project shiro, under directory /core/src/main/java/org/apache/shiro/util/.
Source file: SoftHashMap.java

/** * Creates a new SoftHashMap with the specified retention size. <p/> The retention size (n) is the total number of most recent entries in the map that will be strongly referenced (ie 'retained') to prevent them from being eagerly garbage collected. That is, the point of a SoftHashMap is to allow the garbage collector to remove as many entries from this map as it desires, but there will always be (n) elements retained after a GC due to the strong references. <p/> Note that in a highly concurrent environments the exact total number of strong references may differ slightly than the actual <code>retentionSize</code> value. This number is intended to be a best-effort retention low water mark. * @param retentionSize the total number of most recent entries in the map that will be strongly referenced(retained), preventing them from being eagerly garbage collected by the JVM. */ @SuppressWarnings({"unchecked"}) public SoftHashMap(int retentionSize){ super(); RETENTION_SIZE=Math.max(0,retentionSize); queue=new ReferenceQueue<V>(); strongReferencesLock=new ReentrantLock(); map=new ConcurrentHashMap<K,SoftValue<V,K>>(); strongReferences=new ConcurrentLinkedQueue<V>(); }
Example 41
From project sshj, under directory /src/main/java/net/schmizz/concurrent/.
Source file: Promise.java

/** * Creates this promise with given {@code name}, exception {@code chainer}, and associated {@code lock}. * @param name name of this promise * @param chainer {@link ExceptionChainer} that will be used for chaining exceptions * @param lock lock to use */ public Promise(String name,ExceptionChainer<T> chainer,ReentrantLock lock){ this.name=name; this.chainer=chainer; this.lock=lock == null ? new ReentrantLock() : lock; this.cond=this.lock.newCondition(); }
Example 42
@SuppressWarnings("unchecked") public Grid2D(int sideLength,int cellCount){ this.cellSideLength=sideLength / cellCount; this.cellCount=cellCount; cells=new HashSet[cellCount][cellCount]; locks=new Lock[cellCount][cellCount]; for (int i=0; i < cellCount; ++i) { for (int j=0; j < cellCount; ++j) { cells[i][j]=new HashSet<SWGObject>(); locks[i][j]=new ReentrantLock(); } } }
Example 43
From project Tanks_1, under directory /src/org/apache/mina/transport/vmpipe/.
Source file: VmPipeSession.java

VmPipeSession(IoService service,IoServiceListenerSupport serviceListeners,VmPipeAddress localAddress,IoHandler handler,VmPipe remoteEntry){ super(service); config=new DefaultVmPipeSessionConfig(); this.serviceListeners=serviceListeners; lock=new ReentrantLock(); this.localAddress=localAddress; remoteAddress=serviceAddress=remoteEntry.getAddress(); filterChain=new VmPipeFilterChain(this); receivedMessageQueue=new LinkedBlockingQueue<Object>(); remoteSession=new VmPipeSession(this,remoteEntry); }
Example 44
From project UniversalMediaServer, 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 45
From project Vega, under directory /platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/.
Source file: ScanInstance.java

void setTransientState(ObjectContainer database,ScanAlertFactory alertFactory){ this.database=database; this.alertFactory=alertFactory; this.lock=new ReentrantLock(); this.eventManager=new EventListenerManager(); }
Example 46
From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/windowing/.
Source file: Window.java

/** * Creates a new window with the specified max window size. This constructor enables automatic recurring tasks to be executed (such as expiration of requests). * @param size The maximum number of requests permitted tobe outstanding (unacknowledged) at a given time. Must be > 0. * @param executor The scheduled executor service to executerecurring tasks (such as expiration of requests). * @param monitorInterval The number of milliseconds between executions ofmonitoring tasks. * @param listener A listener to send window events to * @param monitorThreadName The thread name we'll change to when a monitorrun is executed. Null if no name change is required. */ public Window(int size,ScheduledExecutorService executor,long monitorInterval,WindowListener<K,R,P> listener,String monitorThreadName){ if (size <= 0) { throw new IllegalArgumentException("size must be > 0"); } this.maxSize=size; this.futures=new ConcurrentHashMap<K,DefaultWindowFuture<K,R,P>>(size * 2); this.lock=new ReentrantLock(); this.completedCondition=this.lock.newCondition(); this.pendingOffers=new AtomicInteger(0); this.pendingOffersAborted=new AtomicBoolean(false); this.executor=executor; this.monitorInterval=monitorInterval; this.listeners=new CopyOnWriteArrayList<UnwrappedWeakReference<WindowListener<K,R,P>>>(); if (listener != null) { this.listeners.add(new UnwrappedWeakReference<WindowListener<K,R,P>>(listener)); } if (this.executor != null) { this.monitor=new WindowMonitor(this,monitorThreadName); this.monitorHandle=this.executor.scheduleWithFixedDelay(this.monitor,this.monitorInterval,this.monitorInterval,TimeUnit.MILLISECONDS); } else { this.monitor=null; this.monitorHandle=null; } }
Example 47
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 48
From project danbooru-gallery-android, under directory /src/tw/idv/palatis/danboorugallery/utils/.
Source file: PageCursor.java

public PostIterator(PageCursor page_cursor){ this.requesting=new ReentrantLock(); this.page_cursor=page_cursor; this.post_queue=new LinkedBlockingDeque<Post>(); if (synchronous) { for ( Post post : page_cursor.getNextPage()) { post_queue.addLast(post); } } else { if (requesting.tryLock()) { (new AsyncGetPage()).execute(); } else { D.Log.v("Failed to obtain reqlock"); } } }
Example 49
From project DirectMemory, under directory /integrations/ehcache/src/main/java/org/apache/directmemory/ehcache/.
Source file: DirectMemoryStore.java

private void init(long offHeapSizeBytes){ logger.info(" ___ __ __ _ _ ____ _ "); logger.info(" / _ \\ / _|/ _| | | | ___ __ _ _ __/ ___|| |_ ___ _ __ ___ "); logger.info(" | | | | |_| |_| |_| |/ _ \\/ _` | '_ \\___ \\| __/ _ \\| '__/ _ \\"); logger.info(" | |_| | _| _| _ | __/ (_| | |_) |__) | || (_) | | | __/"); logger.info(" \\___/|_| |_| |_| |_|\\___|\\__,_| .__/____/ \\__\\___/|_| \\___|"); logger.info(" |_| "); logger.info("default buffer size = " + DEFAULT_BUFFER_SIZE); logger.info("off heap size = " + offHeapSizeBytes); int numberOfBuffers=(int)(offHeapSizeBytes / DEFAULT_BUFFER_SIZE); logger.info("no of buffers = " + numberOfBuffers); this.bufferLocks=new ArrayList<ReentrantLock>(numberOfBuffers); for (int i=0; i < numberOfBuffers; i++) { this.bufferLocks.add(new ReentrantLock()); } directMemoryCache=new DirectMemoryCache<Object,Element>(numberOfBuffers,(int)(offHeapSizeBytes / numberOfBuffers)); }
Example 50
From project greenDAO, under directory /DaoCore/src/de/greenrobot/dao/.
Source file: LazyList.java

LazyList(AbstractDao<E,?> dao,Cursor cursor,boolean cacheEntities){ this.dao=dao; this.cursor=cursor; size=cursor.getCount(); if (cacheEntities) { entities=new ArrayList<E>(size); for (int i=0; i < size; i++) { entities.add(null); } } else { entities=null; } if (size == 0) { cursor.close(); } lock=new ReentrantLock(); }
Example 51
From project gs-algo, under directory /src/org/graphstream/algorithm/generator/.
Source file: URLGenerator.java

public URLGenerator(String... startFrom){ urls=new HashSet<String>(); stepUrls=new LinkedList<String>(); newUrls=new HashSet<String>(); hrefPattern=Pattern.compile(REGEX); mode=Mode.HOST; filters=new LinkedList<URLFilter>(); directed=false; step=0; printProgress=false; lock=new ReentrantLock(); declineMatchingURL("^(javascript:|mailto:|#).*"); declineMatchingURL(".*[.](avi|tar|gz|zip|mp3|mpg|jpg|jpeg|png|ogg|flv)$"); setUseInternalGraph(true); if (startFrom != null) { for (int i=0; i < startFrom.length; i++) { stepUrls.add(startFrom[i]); } } }
Example 52
From project hoop, under directory /hoop-server/src/main/java/com/cloudera/lib/service/instrumentation/.
Source file: InstrumentationService.java

@Override @SuppressWarnings("unchecked") public void init() throws ServiceException { timersSize=getServiceConfig().getInt(CONF_TIMERS_SIZE,10); counterLock=new ReentrantLock(); timerLock=new ReentrantLock(); variableLock=new ReentrantLock(); samplerLock=new ReentrantLock(); jvmVariables=new ConcurrentHashMap<String,VariableHolder>(); counters=new ConcurrentHashMap<String,Map<String,AtomicLong>>(); timers=new ConcurrentHashMap<String,Map<String,Timer>>(); variables=new ConcurrentHashMap<String,Map<String,VariableHolder>>(); samplers=new ConcurrentHashMap<String,Map<String,Sampler>>(); samplersList=new ArrayList<Sampler>(); all=new LinkedHashMap<String,Map<String,?>>(); all.put("os-env",System.getenv()); all.put("sys-props",(Map<String,?>)(Map)System.getProperties()); all.put("jvm",jvmVariables); all.put("counters",(Map)counters); all.put("timers",(Map)timers); all.put("variables",(Map)variables); all.put("samplers",(Map)samplers); jvmVariables.put("free.memory",new VariableHolder<Long>(new Instrumentation.Variable<Long>(){ public Long getValue(){ return Runtime.getRuntime().freeMemory(); } } )); jvmVariables.put("max.memory",new VariableHolder<Long>(new Instrumentation.Variable<Long>(){ public Long getValue(){ return Runtime.getRuntime().maxMemory(); } } )); jvmVariables.put("total.memory",new VariableHolder<Long>(new Instrumentation.Variable<Long>(){ public Long getValue(){ return Runtime.getRuntime().totalMemory(); } } )); }
Example 53
From project jdcbot, under directory /src/org/elite/jdcbot/framework/.
Source file: MultiHubsAdapter.java

/** * Creates a new instance of MultiHubsAdapter. There should always be only instance of this class. For explanation of the parameters see {@link jDCBot#jDCBot(String,String,int,int,String,String,String,String,String,int,int,boolean) jDCBot Constrcutor}. * @param botname * @param botIP * @param listenPort * @param UDP_listenPort * @param password * @param description * @param conn_type * @param email * @param sharesize * @param uploadSlots * @param downloadSlots * @param passive * @throws IOException * @throws BotException */ public MultiHubsAdapter(String botname,String botIP,int listenPort,int UDP_listenPort,String password,String description,String conn_type,String email,String sharesize,int uploadSlots,int downloadSlots,boolean passive) throws IOException, BotException { if (!GlobalFunctions.isUserNameValid(botname)) { throw new BotException(BotException.Error.INVALID_USERNAME); } _botname=botname; _password=password; _description=description; _conn_type=conn_type; _email=email; _sharesize=sharesize; _maxUploadSlots=uploadSlots; _maxDownloadSlots=downloadSlots; _botIP=botIP; _listenPort=listenPort; _passive=passive; _udp_port=UDP_listenPort; lock=new ReentrantLock(); bots=Collections.synchronizedList(new ArrayList<jDCBot>(6)); hubMap=Collections.synchronizedMap(new HashMap<String,Hub>(6)); shareManager=null; if (_sharesize == null || _sharesize.isEmpty()) _sharesize="0"; socketServer=new BufferedServerSocket(_listenPort); socketServer.setSoTimeout(60000); initiateUDPListening(); }
Example 54
From project org.openscada.atlantis, under directory /org.openscada.da.datasource/src/org/openscada/da/datasource/base/.
Source file: AbstractDataSourceHandler.java

public AbstractDataSourceHandler(final ObjectPoolTracker poolTracker){ this.poolTracker=poolTracker; this.serviceListener=new ServiceListener(){ @Override public void dataSourceChanged( final DataSource dataSource){ AbstractDataSourceHandler.this.setDataSource(dataSource); } } ; this.dataSourceListener=new DataSourceListener(){ @Override public void stateChanged( final DataItemValue value){ AbstractDataSourceHandler.this.stateChanged(value); } } ; final ReentrantReadWriteLock lock=new ReentrantReadWriteLock(); this.dataSourceReadLock=lock.readLock(); this.dataSourceWriteLock=lock.writeLock(); this.trackerLock=new ReentrantLock(); }
Example 55
From project spring-integration-aws, under directory /src/main/java/org/springframework/integration/aws/sqs/.
Source file: AmazonSQSRedeliveryCountDeliveryStrategy.java

public void notifyFailure(String messageId){ if (!locks.containsKey(messageId)) locks.putIfAbsent(messageId,new ReentrantLock()); Lock lock=locks.get(messageId); lock.lock(); try { if (!redeliveryCount.containsKey(messageId)) { AtomicInteger failureCount=new AtomicInteger(1); failureCount=redeliveryCount.putIfAbsent(messageId,failureCount); if (failureCount != null) { failureCount.incrementAndGet(); } } else { redeliveryCount.get(messageId).incrementAndGet(); } } finally { lock.unlock(); } }
Example 56
From project erjang, under directory /src/main/java/erjang/console/.
Source file: TTYTextAreaDriver.java

@Override public ReentrantLock getLock(){ if (lock == null) { lock=new kilim.ReentrantLock(); } return lock; }
Example 57
From project tika, under directory /tika-parsers/src/test/java/org/apache/tika/parser/chm/.
Source file: TestChmExtraction.java

public void testMultiThreadedChmExtraction() throws InterruptedException { ExecutorService executor=Executors.newFixedThreadPool(TestParameters.NTHREADS); for (int i=0; i < TestParameters.NTHREADS; i++) { executor.execute(new Runnable(){ public void run(){ Lock mutex=new ReentrantLock(); for ( String fileName : files) { InputStream stream=null; try { stream=TestChmExtraction.class.getResourceAsStream(fileName); CHMDocumentInformation chmDocInfo=CHMDocumentInformation.load(stream); Metadata md=new Metadata(); mutex.lock(); String text=chmDocInfo.getText(); chmDocInfo.getCHMDocInformation(md); assertEquals(TestParameters.VP_CHM_MIME_TYPE,md.toString().trim()); assertTrue(text.length() > 0); } catch ( Exception e) { e.printStackTrace(); } finally { try { stream.close(); } catch ( IOException e) { e.printStackTrace(); } mutex.unlock(); } } } } ); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(500); } }