List of usage examples for java.util.concurrent.locks Lock lock
lock
From source file:org.unitime.timetable.solver.TimetableSolver.java
public Vector getTimetableGridTables(TimetableGridContext context) { Vector models = new Vector(); Query q = (context.getFilter() == null ? null : new Query(context.getFilter())); Lock lock = currentSolution().getLock().readLock(); lock.lock(); try {//from w w w . j a v a 2 s. c o m TimetableModel model = (TimetableModel) currentSolution().getModel(); switch (context.getResourceType()) { case TimetableGridModel.sResourceTypeRoom: for (RoomConstraint rc : model.getRoomConstraints()) { if (!match(q, rc)) continue; models.add(new SolverGridModel(this, rc, context)); } break; case TimetableGridModel.sResourceTypeInstructor: for (InstructorConstraint ic : model.getInstructorConstraints()) { if (!match(q, ic.getName())) continue; models.add(new SolverGridModel(this, ic, context)); } break; case TimetableGridModel.sResourceTypeDepartment: for (DepartmentSpreadConstraint dc : model.getDepartmentSpreadConstraints()) { if (!match(q, dc.getName())) continue; models.add(new SolverGridModel(this, dc, context)); } if (model.getDepartmentSpreadConstraints().isEmpty()) { org.cpsolver.ifs.assignment.Assignment<Lecture, Placement> assignment = currentSolution() .getAssignment(); Map<Department, Set<Long>> dept2class = new HashMap<Department, Set<Long>>(); for (Object[] pair : (List<Object[]>) DepartmentDAO.getInstance().getSession().createQuery( "select c.controllingDept, c.uniqueId from Class_ c where c.managingDept.solverGroup.uniqueId in :solverGroupIds") .setParameterList("solverGroupIds", getOwnerId(), new LongType()).list()) { Department dept = (Department) pair[0]; Long classId = (Long) pair[1]; Set<Long> classIds = dept2class.get(dept); if (classIds == null) { classIds = new HashSet<Long>(); dept2class.put(dept, classIds); } classIds.add(classId); } for (Department d : new TreeSet<Department>(dept2class.keySet())) { if (!match(q, d.getShortLabel())) continue; Set<Long> classIds = dept2class.get(d); int size = 0; List<Placement> placements = new ArrayList<Placement>(); for (Lecture lecture : currentSolution().getModel().variables()) { if (classIds.contains(lecture.getClassId())) { size++; Placement placement = assignment.getValue(lecture); if (placement != null) placements.add(placement); } } if (size > 0) models.add(new SolverGridModel(this, TimetableGridModel.sResourceTypeDepartment, d.getUniqueId(), d.getShortLabel(), size, placements, context)); } } break; case TimetableGridModel.sResourceTypeCurriculum: Hashtable<String, List<Student>> curricula = new Hashtable<String, List<Student>>(); boolean hasCurricula = false; HashSet<String> ignore = new HashSet<String>(), tested = new HashSet<String>(); for (Student student : model.getAllStudents()) { if (student.getCurriculum() != null && student.getAcademicClassification() != null) { if (!hasCurricula) { curricula.clear(); hasCurricula = true; } String c = student.getCurriculum() + " " + student.getAcademicClassification(); if (tested.add(c) && !match(q, c)) ignore.add(c); if (ignore.contains(c)) continue; List<Student> students = curricula.get(c); if (students == null) { students = new ArrayList<Student>(); curricula.put(c, students); } students.add(student); } else if (!hasCurricula && student.getAcademicArea() != null && student.getAcademicClassification() != null) { String c = student.getAcademicArea() + (student.getMajor() == null ? "" : " " + student.getMajor()) + " " + student.getAcademicClassification(); if (tested.add(c) && !match(q, c)) ignore.add(c); if (ignore.contains(c)) continue; List<Student> students = curricula.get(c); if (students == null) { students = new ArrayList<Student>(); curricula.put(c, students); } students.add(student); } } for (Map.Entry<String, List<Student>> curriculum : curricula.entrySet()) { models.add(new SolverGridModel(this, curriculum.getKey(), curriculum.getValue(), context)); } break; case TimetableGridModel.sResourceTypeSubjectArea: org.cpsolver.ifs.assignment.Assignment<Lecture, Placement> assignment = currentSolution() .getAssignment(); Map<SubjectArea, Set<Long>> sa2class = new HashMap<SubjectArea, Set<Long>>(); for (Object[] pair : (List<Object[]>) DepartmentDAO.getInstance().getSession().createQuery( "select co.subjectArea, c.uniqueId from Class_ c inner join c.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings co where co.isControl = true and c.managingDept.solverGroup.uniqueId in :solverGroupIds") .setParameterList("solverGroupIds", getOwnerId(), new LongType()).list()) { SubjectArea sa = (SubjectArea) pair[0]; Long classId = (Long) pair[1]; Set<Long> classIds = sa2class.get(sa); if (classIds == null) { classIds = new HashSet<Long>(); sa2class.put(sa, classIds); } classIds.add(classId); } for (SubjectArea sa : new TreeSet<SubjectArea>(sa2class.keySet())) { if (!match(q, sa.getSubjectAreaAbbreviation())) continue; Set<Long> classIds = sa2class.get(sa); int size = 0; List<Placement> placements = new ArrayList<Placement>(); for (Lecture lecture : currentSolution().getModel().variables()) { if (classIds.contains(lecture.getClassId())) { size++; Placement placement = assignment.getValue(lecture); if (placement != null) placements.add(placement); } } if (size > 0) models.add(new SolverGridModel(this, TimetableGridModel.sResourceTypeSubjectArea, sa.getUniqueId(), sa.getSubjectAreaAbbreviation(), size, placements, context)); } break; } } finally { lock.unlock(); } return models; }
From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Schedules a new task/* w w w. j a v a 2 s. co m*/ * * @param task the <code>ScheduledTaskWrapper</code> to schedule * @param delay the delay in the scheduling (it must be greater than 1 second * otherwise the delay is set automatically to 1 sec) */ protected void scheduleTask(ScheduledTaskWrapper task, long delay) { if (task == null) { if (log.isTraceEnabled()) { log.trace("Trying to schedule a null task. Request rejected"); } return; } // // We don't get any task lock, but the caller should do (see updateTask or // removeTask or scheduleTask(ScheduledTaskWrapper)) // // // This is used below...see there for a description // Lock taskExecutionLock = null; try { if (!ScheduledTaskWrapper.State.CONFIGURED.equals(task.getState()) && !ScheduledTaskWrapper.State.SCHEDULED.equals(task.getState())) { // // We log the error creating an empty exception in order to have // the stacktrace // log.error("Trying to schedule a not configured or scheduled task. Request rejected", new Exception()); return; } long period = task.getPeriod(); TimeUnit timeUnit = TimeUnit.MILLISECONDS; if (period == 0) { period = 1; timeUnit = TimeUnit.NANOSECONDS; } if (log.isTraceEnabled()) { log.trace("Scheduling task: " + task); } // // We use the execution lock to avoid the task execution before putting // it in the scheduledFutures map. // See ScheduledTaskWrapper.execute // taskExecutionLock = new ReentrantLock(); taskExecutionLock.lock(); task.setExecutionLock(taskExecutionLock); ScheduledFuture scheduledFuture = scheduleWithFixedDelay(task, delay, period, timeUnit); task.setState(ScheduledTaskWrapper.State.SCHEDULED); // // Since DualHashBidiMap is not synchronized we need to sync the write // access // synchronized (scheduledFutures) { scheduledFutures.put(task, scheduledFuture); } } finally { taskExecutionLock.unlock(); } }
From source file:com.mirth.connect.donkey.server.channel.Channel.java
public void invalidateQueues() { sourceQueue.invalidate(true, false); for (DestinationChainProvider chainProvider : destinationChainProviders) { for (Integer metaDataId : chainProvider.getMetaDataIds()) { DestinationQueue queue = chainProvider.getDestinationConnectors().get(metaDataId).getQueue(); /*//from w ww. ja va2s. c om * Before invalidating first obtain a write lock from the queue. This is done so * that no queue threads can commit an updated status to the database while the * invalidation is happening. */ Lock lock = queue.getInvalidationLock(); lock.lock(); try { queue.invalidate(true, false); } finally { lock.unlock(); } } } }
From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java
@NotNull private ReentrantReadWriteLock getUserLock(@NotNull UserInfo userInfo, boolean createOnMissing) throws AzureCmdException { Lock lock = createOnMissing ? userMapLock.writeLock() : userMapLock.readLock(); lock.lock(); try {/*from ww w. j a v a2 s . c o m*/ if (!lockByUser.containsKey(userInfo)) { if (createOnMissing) { lockByUser.put(userInfo, new ReentrantReadWriteLock(false)); } else { throw new AzureCmdException("No access token for the specified User Information"); } } return lockByUser.get(userInfo); } finally { lock.unlock(); } }
From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java
@NotNull private ReentrantReadWriteLock getSubscriptionLock(@NotNull String subscriptionId, boolean createOnMissing) throws AzureCmdException { Lock lock = createOnMissing ? subscriptionMapLock.writeLock() : subscriptionMapLock.readLock(); lock.lock(); try {/* w w w .ja v a2 s . c o m*/ if (!lockBySubscriptionId.containsKey(subscriptionId)) { if (createOnMissing) { lockBySubscriptionId.put(subscriptionId, new ReentrantReadWriteLock(false)); } else { throw new AzureCmdException("No authentication information for the specified Subscription Id"); } } return lockBySubscriptionId.get(subscriptionId); } finally { lock.unlock(); } }
From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java
public void nextTest() { // TODO Auto-generated method stub System.out.println("unlock"); batchExec.setCanStartAnother(true);/*ww w .j a v a 2 s . c om*/ Lock batchLock = batchExec.getLock(); batchLock.lock(); { batchExec.getIsResetted().signalAll(); } batchLock.unlock(); }
From source file:org.apache.hadoop.hive.metastore.HiveMetaStore.java
private static void signalOtherThreadsToStart(final TServer server, final Lock startLock, final Condition startCondition, final AtomicBoolean startedServing) { // A simple thread to wait until the server has started and then signal the other threads to // begin//from ww w . j av a 2 s .c o m Thread t = new Thread() { @Override public void run() { do { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.warn("Signalling thread was interuppted: " + e.getMessage()); } } while (!server.isServing()); startLock.lock(); try { startedServing.set(true); startCondition.signalAll(); } finally { startLock.unlock(); } } }; t.start(); }
From source file:org.apache.hadoop.hive.metastore.HiveMetaStore.java
/** * Start threads outside of the thrift service, such as the compactor threads. * @param conf Hive configuration object *//*from w w w . ja v a 2 s . co m*/ private static void startMetaStoreThreads(final HiveConf conf, final Lock startLock, final Condition startCondition, final AtomicBoolean startedServing) { // A thread is spun up to start these other threads. That's because we can't start them // until after the TServer has started, but once TServer.serve is called we aren't given back // control. Thread t = new Thread() { @Override public void run() { // This is a massive hack. The compactor threads have to access packages in ql (such as // AcidInputFormat). ql depends on metastore so we can't directly access those. To deal // with this the compactor thread classes have been put in ql and they are instantiated here // dyanmically. This is not ideal but it avoids a massive refactoring of Hive packages. // // Wrap the start of the threads in a catch Throwable loop so that any failures // don't doom the rest of the metastore. startLock.lock(); try { JvmPauseMonitor pauseMonitor = new JvmPauseMonitor(conf); pauseMonitor.start(); } catch (Throwable t) { LOG.warn("Could not initiate the JvmPauseMonitor thread." + " GCs and Pauses may not be " + "warned upon.", t); } try { // Per the javadocs on Condition, do not depend on the condition alone as a start gate // since spurious wake ups are possible. while (!startedServing.get()) startCondition.await(); startCompactorInitiator(conf); startCompactorWorkers(conf); startCompactorCleaner(conf); startHouseKeeperService(conf); } catch (Throwable e) { LOG.error("Failure when starting the compactor, compactions may not happen, " + StringUtils.stringifyException(e)); } finally { startLock.unlock(); } ReplChangeManager.scheduleCMClearer(conf); } }; t.setDaemon(true); t.setName("Metastore threads starter thread"); t.start(); }