List of usage examples for java.util.concurrent.locks Lock unlock
void unlock();
From source file:org.apache.synapse.startup.tasks.RegistryResourceFetcher.java
public void execute() { Lock readerLock = lock.readLock(); readerLock.lock();/*from w w w . j a v a 2 s . com*/ try { boolean execute = false; executionCount++; if (state == State.SUSPENDED) { if (executionCount >= maxSuspendThreshold) { execute = true; } } else if (state == State.BACK_OFF) { if (nextSuspendExecutionCount == executionCount) { nextSuspendExecutionCount = nextSuspendExecutionCount * backOffFactor; execute = true; } } else if (state == State.SUSPECT || state == State.ACTIVE) { execute = true; } if (!execute) { if (log.isDebugEnabled()) { log.debug("Skipping the execution because the Registry Fetching is at SUSPENDED state"); } return; } for (RegistryResourceEntry key : registryResources) { if (state == State.ACTIVE) { Entry entry = synapseConfiguration.getEntryDefinition(key.getPath()); if (entry == null) { log.warn("A non remote entry has being specified: " + key.getPath()); return; } if (key.getType().equals(SEQUENCE)) { entry.setMapper(MediatorFactoryFinder.getInstance()); } else if (key.getType().equals(ENDPOINT)) { entry.setMapper(XMLToEndpointMapper.getInstance()); } fetchEntry(key.getPath()); } } lastExecutionTime = System.currentTimeMillis(); } finally { readerLock.unlock(); } }
From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java
public void endDivorce() { Lock lock = rwDivorceLock.writeLock(); lock.lock();//from ww w. java2s. c o m try { String spouseName = StringUtils.EMPTY; if (person.getDivorce() != null) { spouseName = person.getDivorce().getPlayerName(); firePlayerMemberChangeEvent(spouseName, SocialNetworkCommandType.divorce, Type.preRemove, true); } person.setDivorce(null); socialDivorce = null; if (StringUtils.isNotEmpty(spouseName)) { firePlayerMemberChangeEvent(spouseName, SocialNetworkCommandType.divorce, Type.postRemove, true); } } finally { lock.unlock(); } }
From source file:org.opendedup.collections.ShardedProgressiveFileBasedCSMap.java
@Override public boolean remove(ChunkData cm) throws IOException { if (this.isClosed()) { throw new IOException("hashtable [" + this.fileName + "] is close"); }/*w ww .ja v a 2s . co m*/ Lock l = gcLock.readLock(); l.lock(); try { if (!runningGC && !lbf.mightContain(cm.getHash())) return false; try { if (cm.getHash().length == 0) return true; AbstractShard m = this.getReadMap(cm.getHash(), true); if (m == null) return false; if (!m.remove(cm.getHash())) { return false; } else { cm.setmDelete(true); if (this.isClosed()) { throw new IOException("hashtable [" + this.fileName + "] is close"); } try { this.kSz.decrementAndGet(); } catch (Exception e) { } return true; } } catch (Exception e) { SDFSLogger.getLog().fatal("error getting record", e); return false; } } finally { l.unlock(); } }
From source file:org.apache.sling.scripting.sightly.impl.engine.UnitLoader.java
/** * Create a render unit from the given resource * * @param scriptResource the resource//from w w w .ja v a 2 s . co m * @param bindings the bindings * @param renderContext the rendering context * @return the render unit */ public RenderUnit createUnit(Resource scriptResource, Bindings bindings, RenderContextImpl renderContext) { Lock lock = null; try { SourceIdentifier sourceIdentifier = obtainIdentifier(scriptResource); Object obj; ResourceMetadata resourceMetadata = scriptResource.getResourceMetadata(); String encoding = resourceMetadata.getCharacterEncoding(); if (encoding == null) { encoding = sightlyEngineConfiguration.getEncoding(); } SlingHttpServletResponse response = (SlingHttpServletResponse) bindings.get(SlingBindings.RESPONSE); response.setCharacterEncoding(encoding); ResourceResolver adminResolver = renderContext.getScriptResourceResolver(); if (needsUpdate(sourceIdentifier)) { synchronized (activeWrites) { String sourceFullPath = sourceIdentifier.getSourceFullPath(); lock = activeWrites.get(sourceFullPath); if (lock == null) { lock = new ReentrantLock(); activeWrites.put(sourceFullPath, lock); } lock.lock(); } Resource javaClassResource = createClass(adminResolver, sourceIdentifier, bindings, encoding, renderContext); obj = sightlyJavaCompilerService.compileSource(javaClassResource, sourceIdentifier.getFullyQualifiedName()); } else { obj = sightlyJavaCompilerService.getInstance(adminResolver, null, sourceIdentifier.getFullyQualifiedName()); } if (!(obj instanceof RenderUnit)) { throw new SightlyException("Class is not a RenderUnit instance"); } return (RenderUnit) obj; } finally { if (lock != null) { lock.unlock(); } } }
From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java
public void breakMarriage() { Lock lock = rwMarriageLock.writeLock(); lock.lock();/*from w w w . j a v a2s . c o m*/ try { String spouseName = StringUtils.EMPTY; if (person.getMarriage() != null) { spouseName = person.getMarriage().getPlayerName(); firePlayerMemberChangeEvent(spouseName, SocialNetworkCommandType.marriage, Type.preRemove, true); } person.setMarriage(null); socialMarriage = null; if (StringUtils.isNotEmpty(spouseName)) { firePlayerMemberChangeEvent(spouseName, SocialNetworkCommandType.marriage, Type.postRemove, true); } } finally { lock.unlock(); } }
From source file:org.opendedup.collections.ShardedProgressiveFileBasedCSMap.java
@Override public boolean claimKey(byte[] hash, long val, long ct) throws IOException { Lock l = gcLock.readLock(); l.lock();//from ww w . jav a 2 s . c o m try { if (!runningGC && !lbf.mightContain(hash)) { return false; } AbstractShard k = this.keyLookup.getIfPresent(new ByteArrayWrapper(hash)); if (k != null) { try { boolean pos = k.claim(hash, val, ct); if (pos) { // m.cache(); return pos; } } catch (MapClosedException e) { this.keyLookup.invalidate(new ByteArrayWrapper(hash)); } } for (AbstractShard m : this.maps.getAL()) { try { boolean pos = m.claim(hash, val, ct); if (pos) { // m.cache(); return pos; } } catch (MapClosedException e) { } } SDFSLogger.getLog().info("miss2"); return false; } finally { l.unlock(); } }
From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java
/** * Removes all the messages of every type of the given person. * @param fromPlayerName// w w w.j a v a 2 s . c o m * @param messageClass * @return */ public void removeMessagesFrom(SocialPerson fromPerson) { Lock lock = rwMessageQueueLock.writeLock(); lock.lock(); try { // go through every class in the message queue and remove the player list from it for (String className : person.getMessageQueue().keySet()) { // remove the person person.getMessageQueue().get(className).remove(fromPerson.getName()); // if the message type list is empty, remove it also, just to save object memory if (person.getMessageQueue().get(className).keySet().size() == 0) { person.getMessageQueue().remove(className); } } } finally { lock.unlock(); } }
From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java
/** * Convenience method for a multi map add. Also makes sure that all the actual versions line up. *///from www. j av a2 s. c o m private void addToResolutionMap(final Map resolutionMap, final VersionResolution resolution) { Lock lock = (Lock) resolutionMapLocks.get(resolution.getDependencyName()); // lock to protect mutation on the list per dependency as this can potentially run in multiple threads lock.lock(); try { List resolutions = (List) resolutionMap.get(resolution.getDependencyName()); if (resolutions == null) { resolutions = new ArrayList(); resolutionMap.put(resolution.getDependencyName(), resolutions); } for (Iterator it = resolutions.iterator(); it.hasNext();) { final VersionResolution existingResolution = (VersionResolution) it.next(); // TODO: It might be reasonable to fail the build in this case. However, I have yet to see // this message... :-) if (!existingResolution.getActualVersion().equals(resolution.getActualVersion())) { LOG.warn("Dependency '{} expects version '{}' but '{}' already resolved to '{}'!", new Object[] { resolution.getDependencyName(), resolution.getActualVersion(), existingResolution.getDependencyName(), existingResolution.getActualVersion() }); } } LOG.debug("Adding resolution: {}", resolution); resolutions.add(resolution); } finally { lock.unlock(); } }
From source file:org.ng200.openolympus.services.TestingService.java
private SolutionJudge compileSolution(final Solution solution, final SolutionJudge judge, final Properties properties) throws ExecutionException { if (this.dataProvider == null) { throw new IllegalStateException("Shared data provider is null!"); }/*w w w . j a v a 2 s.c o m*/ final Lock lock = solution.getTask().readLock(); lock.lock(); try { TestingService.logger.info("Scheduling solution {} for compilation.", solution.getId()); final JPPFJob job = new JPPFJob(); job.setDataProvider(this.dataProvider); job.setName("Compile solution " + solution.getId()); job.getSLA().setMaxNodes(1); job.getSLA().setPriority((int) (Integer.MAX_VALUE - solution.getId())); job.getSLA().setDispatchExpirationSchedule(new JPPFSchedule(20000L)); job.getSLA().setMaxDispatchExpirations(5); TaskContainer taskContainer = taskContainerCache.getTaskContainerForTask(solution.getTask()); Thread.currentThread().setContextClassLoader( new URLClassLoader(taskContainer.getClassLoaderURLs().toArray(new URL[0]), Thread.currentThread().getContextClassLoader())); job.add(new JacksonSerializationDelegatingTask<>(new SolutionCompilationTask(judge, Lists.from(storageService.getSolutionFile(solution)), properties), taskContainer.getClassLoaderURLs())); job.setBlocking(false); jppfClient.registerClassLoader(taskContainer.getClassLoader(), job.getUuid()); this.jppfClient.submitJob(job); final JsonTaskExecutionResult<SolutionJudge> result = ((JacksonSerializationDelegatingTask<SolutionJudge, SolutionCompilationTask>) job .awaitResults().get(0)).getResultOrThrowable(); if (result.getError() != null) { throw result.getError(); } return result.getResult(); } catch (final Throwable throwable) { throw new RuntimeException("Couldn't compile solution: ", throwable); } finally { lock.unlock(); } }
From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java
private void massUpdateMilestoneGanttItems(final List<MilestoneGanttItem> milestoneGanttItems, Integer sAccountId) {/* w w w . j a v a 2 s. co m*/ if (CollectionUtils.isNotEmpty(milestoneGanttItems)) { Lock lock = DistributionLockUtil.getLock("gantt-milestone-service" + sAccountId); try { final long now = new GregorianCalendar().getTimeInMillis(); if (lock.tryLock(30, TimeUnit.SECONDS)) { try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); PreparedStatement preparedStatement = connection.prepareStatement( "UPDATE `m_prj_milestone` SET " + "name = ?, `startdate` = ?, `enddate` = ?, " + "`lastUpdatedTime`=?, `owner`=?, `ganttIndex`=? WHERE `id` = ?"); for (int i = 0; i < milestoneGanttItems.size(); i++) { preparedStatement.setString(1, milestoneGanttItems.get(i).getName()); preparedStatement.setDate(2, getDateWithNullValue(milestoneGanttItems.get(i).getStartDate())); preparedStatement.setDate(3, getDateWithNullValue(milestoneGanttItems.get(i).getEndDate())); preparedStatement.setDate(4, new Date(now)); preparedStatement.setString(5, milestoneGanttItems.get(i).getAssignUser()); preparedStatement.setInt(6, milestoneGanttItems.get(i).getGanttIndex()); preparedStatement.setInt(7, milestoneGanttItems.get(i).getId()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); connection.commit(); } } } catch (Exception e) { throw new MyCollabException(e); } finally { DistributionLockUtil.removeLock("gantt-milestone-service" + sAccountId); lock.unlock(); } } }