List of usage examples for java.util.concurrent.locks Lock unlock
void unlock();
From source file:com.cip.crane.agent.sheduler.ExecuteTaskThread.java
@Override public void run() { Lock lock = LockHelper.getLock(taskAttempt); ScheduleConf conf = null;/*from w w w . j a v a 2s .c om*/ ScheduleStatus status = null; try { lock.lock(); conf = (ScheduleConf) cs.getConf(localIp, taskAttempt); status = (ScheduleStatus) cs.getStatus(localIp, taskAttempt); cs.addRunningJob(localIp, taskAttempt); status.setStatus(ScheduleStatus.EXECUTING); cs.updateStatus(localIp, taskAttempt, status); } catch (Exception e) { LOGGER.error(e, e); } finally { lock.unlock(); } try { executeJob(conf, status); } catch (Exception e) { LOGGER.error(e, e); status.setStatus(ScheduleStatus.EXECUTE_FAILED); cs.removeRunningJob(localIp, taskAttempt); } try { lock.lock(); cs.updateConf(localIp, taskAttempt, conf); ScheduleStatus thisStatus = (ScheduleStatus) cs.getStatus(localIp, taskAttempt); if (thisStatus.getStatus() != ScheduleStatus.DELETE_SUCCESS) { cs.updateStatus(localIp, taskAttempt, status); cs.removeRunningJob(localIp, taskAttempt); } LOGGER.debug(taskAttempt + " end execute"); } catch (Exception e) { LOGGER.error(e, e); } finally { lock.unlock(); } }
From source file:edu.cornell.mannlib.vitro.webapp.visualization.modelconstructor.factory.OrganizationToPublicationsForSubOrganizationsFactory.java
@Override public Model getOrCreateModel(String uri, Dataset dataset) throws MalformedQueryParametersException { Model candidateModel = ConstructedModelTracker.getModel(ConstructedModelTracker.generateModelIdentifier(uri, OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE)); if (candidateModel != null) { return candidateModel; } else {//from w ww. j a v a 2s . c o m Lock customLock = CustomLock.getLock(); if (customLock.tryLock()) //Acquiring lock if available to construct the model { try { ModelConstructor model = new OrganizationToPublicationsForSubOrganizationsModelConstructor(uri, dataset); Model constructedModel = model.getConstructedModel(); ConstructedModelTracker.trackModel( ConstructedModelTracker.generateModelIdentifier(uri, OrganizationToPublicationsForSubOrganizationsModelConstructor.MODEL_TYPE), constructedModel); return constructedModel; } finally { customLock.unlock(); } } else { log.info("The Model construction process is going on"); return null; } } }
From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java
public Map<String, Integer> getItemCounts() { ObjIntMap<String> counts = HashObjIntMaps.newUpdatableMap(); Lock lock = xLock.readLock(); lock.lock();//from w w w. java2 s . co m try { for (Collection<String> ids : knownItems.values()) { synchronized (ids) { for (String id : ids) { counts.addValue(id, 1); } } } } finally { lock.unlock(); } return counts; }
From source file:gridool.db.sql.ParallelSQLExecJob.java
private static int invokeCopyIntoTable(@Nonnull final ParallelSQLMapTaskResult result, @Nonnull final String outputName, @Nonnull final DBAccessor dba, @Nonnull final LockManager lockMgr, @Nonnull final Timings timings) throws GridException { final File file = getImportingFile(result, outputName); final long filesize = file.length(); int taskNum = result.getTaskNumber(); final String tableName = getTaskResultTableName(outputName, taskNum); final String sql = constructCopyIntoQuery(file, result, tableName); final long mergeTableTime; final int affected; ReadWriteLock systableLock = lockMgr.obtainLock(DBAccessor.SYS_TABLE_SYMBOL); final Lock lock = WORKAROUND_EXLOCK_ON_SYSTBL ? systableLock.writeLock() : systableLock.readLock(); // FIXME REVIEWME why exclusive lock? => sometimes produces wrong result [Trick] read lock for system tables final Connection conn = GridDbUtils.getPrimaryDbConnection(dba, true); lock.lock();// ww w.ja va 2s . c o m final long startMergeTableTime = System.currentTimeMillis(); try { affected = JDBCUtils.update(conn, sql); } catch (SQLException e) { LOG.error(e); throw new GridException("failed to execute a query: " + sql, e); } finally { mergeTableTime = System.currentTimeMillis() - startMergeTableTime; lock.unlock(); JDBCUtils.closeQuietly(conn); new FileDeletionThread(file, LOG).start(); } int expected = result.getNumRows(); if (affected != expected) { String warnmsg = "COPY INTO TABLE failed [Expected: " + expected + ", Inserted: " + affected + ']'; LOG.warn(warnmsg); throw new GridException(warnmsg); } synchronized (timings) { timings.mergeTableTimes.add(mergeTableTime); timings.recievedBytes.add(filesize); timings.recievedRecords.add(affected); } return affected; }
From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java
@Test public void testExclusiveAccess() throws Exception { DefaultLockRepository client1 = new DefaultLockRepository(dataSource); client1.afterPropertiesSet();/* w w w.ja v a 2 s. c o m*/ final DefaultLockRepository client2 = new DefaultLockRepository(dataSource); client2.afterPropertiesSet(); Lock lock1 = new JdbcLockRegistry(client1).obtain("foo"); final BlockingQueue<Integer> data = new LinkedBlockingQueue<Integer>(); final CountDownLatch latch1 = new CountDownLatch(1); lock1.lockInterruptibly(); Executors.newSingleThreadExecutor().execute(() -> { Lock lock2 = new JdbcLockRegistry(client2).obtain("foo"); try { latch1.countDown(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); lock2.lockInterruptibly(); stopWatch.stop(); data.add(4); Thread.sleep(10); data.add(5); Thread.sleep(10); data.add(6); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock2.unlock(); } }); assertTrue(latch1.await(10, TimeUnit.SECONDS)); data.add(1); Thread.sleep(1000); data.add(2); Thread.sleep(1000); data.add(3); lock1.unlock(); for (int i = 0; i < 6; i++) { Integer integer = data.poll(10, TimeUnit.SECONDS); assertNotNull(integer); assertEquals(i + 1, integer.intValue()); } }
From source file:net.myrrix.online.ServerRecommender.java
private static void updateClusters(long id, float[] featureVector, Collection<IDCluster> clusters, Lock clustersReadLock) { if (featureVector == null || clusters == null || clusters.isEmpty()) { return;//from w ww. j a v a2 s .c o m } IDCluster closestCentroid; clustersReadLock.lock(); try { closestCentroid = findClosestCentroid(featureVector, clusters); } finally { clustersReadLock.unlock(); } if (closestCentroid == null) { return; } FastIDSet newMembers = closestCentroid.getMembers(); boolean removeFromCurrentCluster; synchronized (newMembers) { // Wasn't already present, so was present elsewhere; find and remove it removeFromCurrentCluster = newMembers.add(id); } if (removeFromCurrentCluster) { clustersReadLock.lock(); try { for (IDCluster cluster : clusters) { FastIDSet oldMembers = cluster.getMembers(); synchronized (oldMembers) { if (oldMembers.remove(id)) { break; } } } } finally { clustersReadLock.unlock(); } } }
From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java
/** * <p>See {@link #testAsyncSuccess()}.</p> *///from ww w . j av a 2 s. com private void successScenario() throws InterruptedException { String subpath = "/asyncsuccess", body = "hello"; stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body))); final Object[] content = new Object[2]; final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); String result = asyncEndpoint.asyncSuccess(new AsyncHandler<String>() { @Override public void onSuccess(HttpResponse httpResponse, String deserializedContent) { lock.lock(); content[0] = httpResponse; content[1] = deserializedContent; condition.signal(); lock.unlock(); } }); lock.lock(); condition.await(); lock.unlock(); verify(getRequestedFor(urlEqualTo(subpath))); assertTrue(content[0] != null); assertTrue(content[1] != null); assertTrue(content[1].equals(body)); assertNull(result); }
From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java
/** * <p>Tests a successful asynchronous request where the implementation of the * {@link AsyncHandler#onSuccess(HttpResponse, Object)} callback throws an exception.</p> * //from ww w. j a va 2s. c o m * @since 1.3.0 */ @Test public final void testAsyncSuccessCallbackError() throws InterruptedException { String subpath = "/successcallbackerror"; stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200))); final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); asyncEndpoint.asyncSuccessCallbackError(new AsyncHandler<String>() { @Override public void onSuccess(HttpResponse httpResponse, String e) { try { throw new IllegalStateException(); } finally { lock.lock(); condition.signal(); lock.unlock(); } } }); lock.lock(); condition.await(); lock.unlock(); verify(getRequestedFor(urlEqualTo(subpath))); successScenario(); //verify that the asynchronous request executor has survived the exception }
From source file:edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ShibbolethAttributeResolver.java
/** {@inheritDoc} */ public Map<String, BaseAttribute> resolveAttributes(SAMLProfileRequestContext attributeRequestContext) throws AttributeResolutionException { ShibbolethResolutionContext resolutionContext = new ShibbolethResolutionContext(attributeRequestContext); log.debug("{} resolving attributes for principal {}", getId(), attributeRequestContext.getPrincipalName()); if (getAttributeDefinitions().size() == 0) { log.debug("No attribute definitions loaded in {} so no attributes can be resolved for principal {}", getId(), attributeRequestContext.getPrincipalName()); return new HashMap<String, BaseAttribute>(); }/* ww w .j a va 2 s . co m*/ Lock readLock = getReadWriteLock().readLock(); readLock.lock(); Map<String, BaseAttribute> resolvedAttributes = null; try { resolvedAttributes = resolveAttributes(resolutionContext); cleanResolvedAttributes(resolvedAttributes, resolutionContext); } finally { readLock.unlock(); } log.debug(getId() + " resolved, for principal {}, the attributes: {}", attributeRequestContext.getPrincipalName(), resolvedAttributes.keySet()); return resolvedAttributes; }
From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java
/** * <p>Tests asynchronous request execution with @{@link Async} and * {@link AsyncHandler#onError(Exception)}.</p> * //from w w w .ja va2 s .c om * @since 1.3.0 */ @Test public final void testAsyncError() throws InterruptedException { String subpath = "/asyncerror", body = "non-JSON-content"; stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body))); final Object[] content = new Object[1]; final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); asyncEndpoint.asyncError(new AsyncHandler<User>() { @Override public void onSuccess(HttpResponse httpResponse, User user) { } @Override public void onError(InvocationException error) { lock.lock(); content[0] = error; condition.signal(); lock.unlock(); } }); lock.lock(); condition.await(); lock.unlock(); verify(getRequestedFor(urlEqualTo(subpath))); assertTrue(content[0] != null); assertTrue(content[0] instanceof InvocationException); }