List of usage examples for java.util.concurrent.locks Lock lock
lock
From source file:org.unitime.timetable.solver.studentsct.StudentSolver.java
public Map<String, String> statusSolutionInfo() { if (isPassivated()) return (iBestSolutionInfoBeforePassivation == null ? iCurrentSolutionInfoBeforePassivation : iBestSolutionInfoBeforePassivation); java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try {/*from w w w. ja v a 2s . com*/ Map<String, String> info = super.currentSolution().getBestInfo(); try { if (info == null || getSolutionComparator().isBetterThanBestSolution(super.currentSolution())) info = super.currentSolution().getModel().getInfo(super.currentSolution().getAssignment()); } catch (ConcurrentModificationException e) { } return info; } finally { lock.unlock(); } }
From source file:org.opendedup.collections.ShardedProgressiveFileBasedCSMap.java
@Override public synchronized long claimRecords(SDFSEvent evt) throws IOException { if (this.isClosed()) throw new IOException("Hashtable " + this.fileName + " is close"); executor = new ThreadPoolExecutor(Main.writeThreads + 1, Main.writeThreads + 1, 10, TimeUnit.SECONDS, worksQueue, new ProcessPriorityThreadFactory(Thread.MIN_PRIORITY), executionHandler); csz = new AtomicLong(0); try {//from www. j ava2s .c o m Lock l = this.gcLock.writeLock(); l.lock(); this.runningGC = true; try { File _fs = new File(fileName); lbf = null; lbf = new LargeBloomFilter(_fs.getParentFile(), maxSz, .001, true, true, false); } finally { l.unlock(); } SDFSLogger.getLog().info("Claiming Records [" + this.getSize() + "] from [" + this.fileName + "]"); SDFSEvent tEvt = SDFSEvent .claimInfoEvent("Claiming Records [" + this.getSize() + "] from [" + this.fileName + "]", evt); tEvt.maxCt = this.maps.size(); Iterator<AbstractShard> iter = maps.iterator(); ArrayList<ClaimShard> excs = new ArrayList<ClaimShard>(); while (iter.hasNext()) { tEvt.curCt++; AbstractShard m = null; try { m = iter.next(); ClaimShard cms = new ClaimShard(m, csz, lbf); excs.add(cms); executor.execute(cms); } catch (Exception e) { tEvt.endEvent("Unable to claim records for " + m + " because : [" + e.toString() + "]", SDFSEvent.ERROR); SDFSLogger.getLog().error("Unable to claim records for " + m, e); throw new IOException(e); } } executor.shutdown(); try { while (!executor.awaitTermination(10, TimeUnit.SECONDS)) { SDFSLogger.getLog().debug("Awaiting fdisk completion of threads."); } } catch (InterruptedException e) { throw new IOException(e); } for (ClaimShard cms : excs) { if (cms.ex != null) throw new IOException(cms.ex); } this.kSz.getAndAdd(-1 * csz.get()); tEvt.endEvent("removed [" + csz.get() + "] records"); SDFSLogger.getLog().info("removed [" + csz.get() + "] records"); iter = maps.iterator(); while (iter.hasNext()) { AbstractShard m = null; try { m = iter.next(); if (!m.isFull() && !m.isActive()) { // SDFSLogger.getLog().info("deleting " + // m.toString()); m.iterInit(); KVPair p = m.nextKeyValue(); while (p != null) { AbstractShard _m = this.getWriteMap(); try { _m.put(p.key, p.value, p.loc); this.keyLookup.invalidate(new ByteArrayWrapper(p.key)); this.lbf.put(p.key); p = m.nextKeyValue(); } catch (HashtableFullException e) { } } int mapsz = maps.size(); l = this.gcLock.writeLock(); l.lock(); try { maps.remove(m); } finally { l.unlock(); } mapsz = mapsz - maps.size(); SDFSLogger.getLog() .info("removing map " + m.toString() + " sz=" + maps.size() + " rm=" + mapsz); m.vanish(); m = null; } else if (m.isMaxed()) { SDFSLogger.getLog().info("deleting maxed " + m.toString()); m.iterInit(); KVPair p = m.nextKeyValue(); while (p != null) { ShardedFileByteArrayLongMap _m = this.getWriteMap(); try { _m.put(p.key, p.value, p.loc); p = m.nextKeyValue(); } catch (HashtableFullException e) { } } int mapsz = maps.size(); l = this.gcLock.writeLock(); l.lock(); try { maps.remove(m); } finally { l.unlock(); } mapsz = mapsz - maps.size(); SDFSLogger.getLog() .info("removing map " + m.toString() + " sz=" + maps.size() + " rm=" + mapsz); m.vanish(); m = null; } } catch (Exception e) { tEvt.endEvent("Unable to compact " + m + " because : [" + e.toString() + "]", SDFSEvent.ERROR); SDFSLogger.getLog().error("to compact " + m, e); throw new IOException(e); } } l.lock(); this.runningGC = false; l.unlock(); return csz.get(); } finally { executor = null; } }
From source file:org.opendedup.collections.ShardedProgressiveFileBasedCSMap.java
@Override public synchronized long claimRecords(SDFSEvent evt, LargeBloomFilter bf) throws IOException { if (this.isClosed()) throw new IOException("Hashtable " + this.fileName + " is close"); executor = new ThreadPoolExecutor(Main.writeThreads + 1, Main.writeThreads + 1, 10, TimeUnit.SECONDS, worksQueue, new ProcessPriorityThreadFactory(Thread.MIN_PRIORITY), executionHandler); csz = new AtomicLong(0); try {//w w w . java 2 s.com Lock l = this.gcLock.writeLock(); l.lock(); this.runningGC = true; try { File _fs = new File(fileName); lbf = null; lbf = new LargeBloomFilter(_fs.getParentFile(), maxSz, .001, true, true, false); } finally { l.unlock(); } SDFSLogger.getLog().info("Claiming Records [" + this.getSize() + "] from [" + this.fileName + "]"); SDFSEvent tEvt = SDFSEvent .claimInfoEvent("Claiming Records [" + this.getSize() + "] from [" + this.fileName + "]", evt); tEvt.maxCt = this.maps.size(); Iterator<AbstractShard> iter = maps.iterator(); ArrayList<ClaimShard> excs = new ArrayList<ClaimShard>(); while (iter.hasNext()) { tEvt.curCt++; AbstractShard m = null; try { m = iter.next(); ClaimShard cms = new ClaimShard(m, bf, lbf, csz); excs.add(cms); executor.execute(cms); } catch (Exception e) { tEvt.endEvent("Unable to claim records for " + m + " because : [" + e.toString() + "]", SDFSEvent.ERROR); SDFSLogger.getLog().error("Unable to claim records for " + m, e); throw new IOException(e); } } executor.shutdown(); try { while (!executor.awaitTermination(10, TimeUnit.SECONDS)) { SDFSLogger.getLog().debug("Awaiting fdisk completion of threads."); } } catch (InterruptedException e) { throw new IOException(e); } for (ClaimShard cms : excs) { if (cms.ex != null) throw new IOException(cms.ex); } this.kSz.getAndAdd(-1 * csz.get()); tEvt.endEvent("removed [" + csz.get() + "] records"); SDFSLogger.getLog().info("removed [" + csz.get() + "] records"); iter = maps.iterator(); while (iter.hasNext()) { AbstractShard m = null; try { m = iter.next(); if (!m.isFull() && !m.isActive()) { // SDFSLogger.getLog().info("deleting " + // m.toString()); m.iterInit(); KVPair p = m.nextKeyValue(); while (p != null) { AbstractShard _m = this.getWriteMap(); try { _m.put(p.key, p.value, p.loc); this.keyLookup.invalidate(new ByteArrayWrapper(p.key)); this.lbf.put(p.key); p = m.nextKeyValue(); } catch (HashtableFullException e) { } } int mapsz = maps.size(); l = this.gcLock.writeLock(); l.lock(); try { maps.remove(m); } finally { l.unlock(); } mapsz = mapsz - maps.size(); SDFSLogger.getLog() .info("removing map " + m.toString() + " sz=" + maps.size() + " rm=" + mapsz); m.vanish(); m = null; } else if (m.isMaxed()) { SDFSLogger.getLog().info("deleting maxed " + m.toString()); m.iterInit(); KVPair p = m.nextKeyValue(); while (p != null) { ShardedFileByteArrayLongMap _m = this.getWriteMap(); try { _m.put(p.key, p.value); p = m.nextKeyValue(); } catch (HashtableFullException e) { } } int mapsz = maps.size(); l = this.gcLock.writeLock(); l.lock(); try { maps.remove(m); } finally { l.unlock(); } mapsz = mapsz - maps.size(); SDFSLogger.getLog() .info("removing map " + m.toString() + " sz=" + maps.size() + " rm=" + mapsz); m.vanish(); m = null; } } catch (Exception e) { tEvt.endEvent("Unable to compact " + m + " because : [" + e.toString() + "]", SDFSEvent.ERROR); SDFSLogger.getLog().error("to compact " + m, e); throw new IOException(e); } } l.lock(); this.runningGC = false; l.unlock(); return csz.get(); } finally { executor = null; } }
From source file:org.unitime.timetable.solver.studentsct.StudentSolver.java
protected void onFinish() { super.onFinish(); try {/*from w ww . j a v a2s . c om*/ iWorking = true; if (currentSolution().getBestInfo() != null) currentSolution().restoreBest(); if (currentSolution().getBestInfo() != null && getProperties().getPropertyBoolean("General.Save", false)) { StudentSectioningSaver saver = new StudentSectioningDatabaseSaver(this); java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { saver.save(); } catch (Exception e) { Progress.getInstance(currentSolution().getModel()).error(e.getMessage(), e); } finally { lock.unlock(); } } if (getProperties().getPropertyBoolean("General.Unload", false)) { dispose(); } else { Progress.getInstance(currentSolution().getModel()).setStatus("Awaiting commands ..."); } } finally { iWorking = false; } }
From source file:org.unitime.timetable.solver.studentsct.StudentSolver.java
public byte[] exportXml() throws Exception { java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try {//from ww w . j a v a2s . c o m File temp = File.createTempFile("student-" + getSessionId(), ".xml"); boolean anonymize = ApplicationProperty.SolverXMLExportNames.isFalse(); boolean idconv = ApplicationProperty.SolverXMLExportConvertIds.isTrue(); getProperties().setProperty("Xml.SaveBest", "true"); getProperties().setProperty("Xml.SaveInitial", "true"); getProperties().setProperty("Xml.SaveCurrent", "true"); if (anonymize) { getProperties().setProperty("Xml.ConvertIds", idconv ? "true" : "false"); getProperties().setProperty("Xml.SaveOnlineSectioningInfo", "true"); getProperties().setProperty("Xml.SaveStudentInfo", "false"); getProperties().setProperty("Xml.ShowNames", "false"); } StudentSectioningXMLSaver saver = new StudentSectioningXMLSaver(this); ByteArrayOutputStream ret = new ByteArrayOutputStream(); try { saver.save(temp); FileInputStream fis = new FileInputStream(temp); byte[] buf = new byte[16 * 1024]; int read = 0; while ((read = fis.read(buf, 0, buf.length)) > 0) ret.write(buf, 0, read); ret.flush(); ret.close(); fis.close(); } catch (Exception e) { sLog.error(e.getMessage(), e); } temp.delete(); if (anonymize) { getProperties().setProperty("Xml.ConvertIds", "false"); getProperties().setProperty("Xml.SaveOnlineSectioningInfo", "true"); getProperties().setProperty("Xml.SaveStudentInfo", "true"); getProperties().setProperty("Xml.ShowNames", "true"); } return ret.toByteArray(); } finally { lock.unlock(); } }
From source file:org.unitime.timetable.solver.studentsct.StudentSolver.java
public boolean backup(File folder, String puid) { folder.mkdirs();/*from w ww . ja v a 2 s .c o m*/ if (currentSolution() == null) return false; java.util.concurrent.locks.Lock lock = currentSolution().getLock().readLock(); lock.lock(); try { getProperties().setProperty("Xml.SaveBest", "true"); getProperties().setProperty("Xml.SaveInitial", "true"); getProperties().setProperty("Xml.SaveCurrent", "true"); File outXmlFile = new File(folder, "sct_" + puid + BackupFileFilter.sXmlExtension); File outPropertiesFile = new File(folder, "sct_" + puid + BackupFileFilter.sPropertiesExtension); try { new StudentSectioningXMLSaver(this).save(outXmlFile); for (Iterator i = getProperties().entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); if (!(entry.getKey() instanceof String)) { sLog.error("Configuration key " + entry.getKey() + " is not of type String (" + entry.getKey().getClass() + ")"); i.remove(); } else if (!(entry.getValue() instanceof String)) { sLog.error("Value of configuration key " + entry.getKey() + " is not of type String (" + entry.getValue() + " is of type " + entry.getValue().getClass() + ")"); i.remove(); } } FileOutputStream fos = null; try { fos = new FileOutputStream(outPropertiesFile); getProperties().store(fos, "Backup file"); fos.flush(); fos.close(); fos = null; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } return true; } catch (Exception e) { sLog.error(e.getMessage(), e); if (outXmlFile.exists()) outXmlFile.delete(); if (outPropertiesFile.exists()) outPropertiesFile.delete(); } } finally { lock.unlock(); } return false; }
From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Called when a TaskWrapper ends its execution. See afterExecute. *//*from ww w . j a v a 2 s . co m*/ protected void afterTaskExecution(Runnable r, Throwable t) { TaskWrapper taskWrapper = null; if (r instanceof ScheduledFuture) { ScheduledFuture scheduledFuture = (ScheduledFuture) r; Lock handlingTaskLock = null; synchronized (taskFutures) { taskWrapper = (TaskWrapper) taskFutures.getKey(scheduledFuture); if (taskWrapper != null) { handlingTaskLock = getHandlingTaskLock(taskWrapper); handlingTaskLock.lock(); } } try { logTaskWrapperExecutionError(taskWrapper, scheduledFuture); if (taskWrapper == null) { return; } // // we don't need to remove the task from the (ScheduledFuture)queue // because it is already removed since is a one shot task (not scheduled) // synchronized (taskFutures) { taskFutures.remove(taskWrapper); } boolean needRedo = false; //synchronized (taskWrapper) { needRedo = taskWrapper.needRedo(); //} if (needRedo) { long period = taskWrapper.getPeriod(); if (log.isTraceEnabled()) { log.trace("Task '" + taskWrapper + "' must be redone. " + "It will be executed in " + period + " milliseconds"); } ScheduledFuture f = schedule(taskWrapper, period, TimeUnit.MILLISECONDS); synchronized (taskFutures) { taskFutures.put(taskWrapper, f); } } } finally { if (handlingTaskLock != null) { handlingTaskLock.unlock(); } handlingOneShotExecutionTimeInformation(taskWrapper); LogContext.clear(); } } }
From source file:org.jasig.portal.portlet.container.services.PortletPreferencesServiceImpl.java
@Transactional @Override/* w ww . j av a 2 s. co m*/ public void store(PortletWindow plutoPortletWindow, PortletRequest portletRequest, Map<String, PortletPreference> newPreferences) throws PortletContainerException { final HttpServletRequest httpServletRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest); //Determine if the user is a guest final boolean isGuest = isGuestUser(portletRequest); //If this is a guest and no prefs are being stored just return as the rest of the method is not needed for this case if (isGuest && !(this.isStoreInEntity(portletRequest) || this.isStoreInMemory(portletRequest))) { return; } final IPortletWindow portletWindow = this.portletWindowRegistry.convertPortletWindow(httpServletRequest, plutoPortletWindow); IPortletEntity portletEntity = portletWindow.getPortletEntity(); final IPortletEntityId portletEntityId = portletEntity.getPortletEntityId(); final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); final PortletDefinition portletDescriptor = this.portletDefinitionRegistry .getParentPortletDescriptor(portletDefinition.getPortletDefinitionId()); //Is this CONFIG mode final boolean configMode = IPortletRenderer.CONFIG.equals(portletWindow.getPortletMode()); //Get Map of descriptor and definition preferences to check new preferences against final Map<String, PortletPreference> basePreferences = new HashMap<String, PortletPreference>(); //Add deploy preferences final List<IPortletPreference> descriptorPreferencesList = this.getDescriptorPreferences(portletDescriptor); this.addPreferencesToMap(descriptorPreferencesList, basePreferences, configMode); final Lock prefLock; if (configMode) { //In config mode we don't worry about locking prefLock = NoopLock.INSTANCE; } else { prefLock = this.portletEntityRegistry.getPortletEntityLock(httpServletRequest, portletEntityId); } //Do a tryLock firsrt so that we can warn about concurrent preference modification if it fails boolean locked = prefLock.tryLock(); try { if (!locked) { logger.warn("Concurrent portlet preferences modification by: " + portletDefinition.getFName() + " " + "This has the potential for changes to preferences to be lost. " + "This portlet should be modified to synchronize its preference modifications appropriately", new Throwable()); prefLock.lock(); locked = true; //Refresh the portlet entity that may have been changed by the thread we were blocked by if (!configMode) { portletEntity = this.portletEntityRegistry.getPortletEntity(httpServletRequest, portletEntityId); } } //Add definition preferences if not config mode if (!configMode) { final List<IPortletPreference> definitionPreferencesList = portletDefinition .getPortletPreferences(); this.addPreferencesToMap(definitionPreferencesList, basePreferences, false); } final List<IPortletPreference> preferencesList = new ArrayList<IPortletPreference>( newPreferences.size()); for (final PortletPreference internalPreference : newPreferences.values()) { //Ignore preferences with null names final String name = internalPreference.getName(); if (name == null) { throw new IllegalArgumentException("PortletPreference name cannot be null"); } //Convert to a uPortal preference class to ensure quality check and persistence works final IPortletPreference preference = new PortletPreferenceImpl(internalPreference); //If the preference exactly equals a descriptor or definition preference ignore it final PortletPreference basePreference = basePreferences.get(name); if (preference.equals(basePreference)) { continue; } //New preference, add it to the list preferencesList.add(preference); } //If in config mode store the preferences on the definition if (configMode) { portletDefinition.setPortletPreferences(preferencesList); this.portletDefinitionRegistry.updatePortletDefinition(portletDefinition); } //If not a guest or if guest prefs are shared store them on the entity else if (this.isStoreInEntity(portletRequest)) { //Update the portlet entity with the new preferences portletEntity.setPortletPreferences(preferencesList); this.portletEntityRegistry.storePortletEntity(httpServletRequest, portletEntity); } //Must be a guest and share must be off so store the prefs on the session else { //Store memory preferences this.storeSessionPreferences(portletEntityId, httpServletRequest, preferencesList); } } finally { //check if locked, needed due to slighly more complex logic around the tryLock and logging if (locked) { prefLock.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. j a v a2s .c o 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.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Called when a ScheduledTask ends its execution. See afterExecute. *///from w w w . java 2 s. co m protected void afterScheduledTaskExecution(Runnable r, Throwable t) { super.afterExecute(r, t); ScheduledTaskWrapper scheduledTask = null; Lock handlingTaskLock = null; if (r instanceof ScheduledFuture) { ScheduledFuture scheduledFuture = (ScheduledFuture) r; synchronized (scheduledFutures) { scheduledTask = (ScheduledTaskWrapper) scheduledFutures.getKey(scheduledFuture); if (scheduledTask != null) { handlingTaskLock = getHandlingTaskLock(scheduledTask.getId()); handlingTaskLock.lock(); } } // // Bear in mind that here the scheduledTask could be null if the scheduledFuture // has been cancelled and removed from the scheduledFutures map. // if (log.isTraceEnabled()) { if (scheduledTask == null) { log.trace("Scheduled task null for: " + r + ". Is it cancelled ? " + scheduledFuture.isCancelled()); } } try { if (scheduledFuture.isDone()) { scheduledFuture.get(); } } catch (InterruptedException ie) { } catch (ExecutionException ee) { // // This is done to retrieve the possible exception thrown by the // task // Throwable realThrowable = ee.getCause(); if (scheduledTask != null) { log.error("Task '" + scheduledTask + "' throws an uncaught exception. " + "The task will be rescheduled", realThrowable); try { scheduledTask.shutdown(); } catch (TaskException ex) { log.error("Error shutting down scheduled task '" + scheduledTask + "'", ex); } scheduledTask.setState(ScheduledTaskWrapper.State.SHUTDOWN); synchronized (scheduledFutures) { // // Any time we remove the scheduledTask from scheduledFutures, // we try to remove the scheduledFuture from the queue. This // is not really needed because after a while this is performed // automatically but in this way we keep scheduledFutures and // the queue in sync // if (scheduledFuture instanceof Runnable) { super.remove((Runnable) scheduledFuture); } scheduledFutures.remove(scheduledTask); } // // The task will be rescheduled using the period as delay // because otherwise a new execution is performed asap // scheduleTask(scheduledTask, scheduledTask.getPeriod()); } else { log.error("Uncaught exception thrown by: " + scheduledFuture + ". This ScheduledFuture seems not relative to a ScheduleTask" + " so nothing will be rescheduled (it could be about " + " to an already cancelled task)", realThrowable); } } catch (CancellationException ce) { } finally { if (handlingTaskLock != null) { handlingTaskLock.unlock(); } handlingScheduledExecutionTimeInformation(scheduledTask); LogContext.clear(); } } }