List of usage examples for java.util.concurrent.locks Lock tryLock
boolean tryLock();
From source file:org.rhq.core.pc.inventory.InventoryManager.java
@NotNull // TODO (ips): Perhaps refactor this so that it shares code with AvailabilityExecutor.checkInventory(). public Availability getCurrentAvailability(Resource resource) { AvailabilityType availType = null; // i.e. UNKNOWN; ResourceContainer resourceContainer = getResourceContainer(resource); if (resourceContainer != null) { if (resourceContainer.getResourceComponentState() == ResourceComponentState.STARTED) { AvailabilityFacet resourceComponent; Lock lock = resourceContainer.getReadFacetLock(); if (lock.tryLock()) { // We have acquired the lock. try { ResourceCategory resourceCategory = resource.getResourceType().getCategory(); // Give the call to getAvailability() a bit more time if the Resource is a server. long componentTimeout = (resourceCategory == ResourceCategory.SERVER) ? 10000 : 5000; // We already possess the lock, so tell the proxy not to do any locking of its own. resourceComponent = resourceContainer.createResourceComponentProxy(AvailabilityFacet.class, FacetLockType.NONE, componentTimeout, true, true); availType = resourceComponent.getAvailability(); } catch (PluginContainerException e) { log.error("Failed to retrieve ResourceComponent for " + resource + ".", e); } catch (RuntimeException e) { log.error("Call to getAvailability() on ResourceComponent for " + resource + " failed.", e); availType = AvailabilityType.DOWN; } finally { lock.unlock();/*from ww w .ja va2 s . c o m*/ } } else { // Some other thread possesses the lock - return the last-collected availability for the Resource if // there is one. if (resourceContainer.getAvailability() != null) return resourceContainer.getAvailability(); } } } else { log.error("No ResourceContainer exists for " + resource + "."); } return new Availability(resource, availType); }
From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java
@Test public void testOnlyOneLock() throws Exception { for (int i = 0; i < 100; i++) { final List<String> locked = new ArrayList<String>(); final CountDownLatch latch = new CountDownLatch(20); ExecutorService pool = Executors.newFixedThreadPool(6); ArrayList<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(); for (int j = 0; j < 20; j++) { final DefaultLockRepository client = new DefaultLockRepository(this.dataSource); client.afterPropertiesSet(); this.context.getAutowireCapableBeanFactory().autowireBean(client); Callable<Boolean> task = () -> { Lock lock = new JdbcLockRegistry(client).obtain("foo"); try { if (locked.isEmpty() && lock.tryLock()) { if (locked.isEmpty()) { locked.add("done"); return true; }/*from www .j a v a 2s .c om*/ } } finally { try { lock.unlock(); } catch (Exception e) { // ignore } latch.countDown(); } return false; }; tasks.add(task); } logger.info("Starting: " + i); pool.invokeAll(tasks); assertTrue(latch.await(10, TimeUnit.SECONDS)); // eventually they both get the lock and release it assertEquals(1, locked.size()); assertTrue(locked.contains("done")); } }
From source file:org.springframework.integration.redis.util.RedisLockRegistryTests.java
@Test @RedisAvailable/*from w w w . ja v a2 s . co m*/ public void testEquals() throws Exception { RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest(); RedisLockRegistry registry1 = new RedisLockRegistry(connectionFactory, this.registryKey); registry1.setUseWeakReferences(true); RedisLockRegistry registry2 = new RedisLockRegistry(connectionFactory, this.registryKey); RedisLockRegistry registry3 = new RedisLockRegistry(connectionFactory, this.registryKey2); Lock lock1 = registry1.obtain("foo"); Lock lock2 = registry1.obtain("foo"); assertEquals(lock1, lock2); lock1.lock(); lock2.lock(); assertEquals(lock1, lock2); lock1.unlock(); lock2.unlock(); assertEquals(lock1, lock2); lock1 = registry1.obtain("foo"); lock2 = registry2.obtain("foo"); assertNotEquals(lock1, lock2); lock1.lock(); assertFalse(lock2.tryLock()); lock1.unlock(); lock1 = registry1.obtain("foo"); lock2 = registry3.obtain("foo"); assertNotEquals(lock1, lock2); lock1.lock(); lock2.lock(); lock1.unlock(); lock2.unlock(); }
From source file:org.springframework.integration.redis.util.RedisLockRegistryTests.java
@Test @RedisAvailable//from w w w. j a va2 s .c o m public void testExpireNotChanged() throws Exception { RedisConnectionFactory connectionFactory = this.getConnectionFactoryForTest(); final RedisLockRegistry registry = new RedisLockRegistry(connectionFactory, this.registryKey, 10000); Lock lock = registry.obtain("foo"); lock.lock(); Long expire = getExpire(registry, "foo"); Future<Object> result = Executors.newSingleThreadExecutor().submit(() -> { Lock lock2 = registry.obtain("foo"); assertFalse(lock2.tryLock()); return null; }); result.get(); assertEquals(expire, getExpire(registry, "foo")); lock.unlock(); }
From source file:xbird.xquery.ext.grid.DispatchQueryExecTask.java
/** * @see QueryExecJob#map(gridool.routing.GridTaskRouter, DispatchQueryExecTask) *///from w ww . j av a 2 s .c o m public Map<GridTask, GridNode> mapQueryTask(QueryExecJob execJob) throws GridException { checkInjectedResources(); final GridNodeInfo localNode = GridUtils.getLocalNode(config); if (!excludeNodeList.contains(localNode)) { excludeNodeList.add(localNode); } final GridNodeSelector nodeSelector = config.getNodeSelector(); final LockManager lockManager = directory.getLockManager(); final Map<GridNode, List<String>> assignMap = new HashMap<GridNode, List<String>>(relativePaths.size()); final List<Pair<String, Lock>> localExecResources = new ArrayList<Pair<String, Lock>>(relativePaths.size()); int totalLocked = 0; for (String path : relativePaths) { ReadWriteLock lock = lockManager.obtainLock(path); final Lock rlock = lock.readLock(); if (rlock.tryLock()) { localExecResources.add(new Pair<String, Lock>(path, rlock)); } else { totalLocked++; final List<GridNode> replicatedNodes; try { replicatedNodes = directory.exactSearch(path, excludeNodeList); } catch (DbException e) { LOG.error(e.getMessage()); throw new GridException("Exception caused while lookup: " + path, e); } if (replicatedNodes == null || replicatedNodes.isEmpty()) { throw new GridException("No replicated document found for path: " + path); } // TODO Select a node that least recently used for write requests. GridNode node = nodeSelector.selectNode(replicatedNodes, this, config); assert (node != null); List<String> mappedPaths = assignMap.get(node); if (mappedPaths == null) { mappedPaths = new ArrayList<String>(16); assignMap.put(node, mappedPaths); } mappedPaths.add(path); } } final Map<GridTask, GridNode> map = new IdentityHashMap<GridTask, GridNode>(assignMap.size() + 1); for (Map.Entry<GridNode, List<String>> e : assignMap.entrySet()) { GridNode node = e.getKey(); List<String> mappedPaths = e.getValue(); DispatchQueryExecTask dispatchTask = new DispatchQueryExecTask(execJob, bindingVar, bodyExpr, mappedPaths, true); map.put(dispatchTask, node); } if (!localExecResources.isEmpty()) { boolean doForwarding = redirectable; LocalQueryExecTask localTask = new LocalQueryExecTask(execJob, bindingVar, bodyExpr, localExecResources, doForwarding); map.put(localTask, localNode); } if (LOG.isInfoEnabled()) { LOG.info("DispatchQueryExecTask is mapped to " + assignMap.size() + " DispatchQueryExecTask and " + (localExecResources.isEmpty() ? '0' : '1') + " LocalQueryExecTask (" + localExecResources.size() + " localExecResources), " + totalLocked + " documents are write-locked"); } return map; }