Java Code Examples for java.util.concurrent.locks.Lock#unlock()

The following examples show how to use java.util.concurrent.locks.Lock#unlock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityType.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
public static SecurityType create(AccessContext accCtx, SecTypeName typeName)
    throws AccessDeniedException
{
    accCtx.privEffective.requirePrivileges(Privilege.PRIV_SYS_ALL);

    Lock writeLock = GLOBAL_TYPE_MAP_LOCK.writeLock();

    SecurityType secTypeObj;
    try
    {
        writeLock.lock();
        secTypeObj = GLOBAL_TYPE_MAP.get(typeName);
        if (secTypeObj == null)
        {
            secTypeObj = new SecurityType(typeName);
            GLOBAL_TYPE_MAP.put(typeName, secTypeObj);
        }
    }
    finally
    {
        writeLock.unlock();
    }
    return secTypeObj;
}
 
Example 2
Source File: XdsModel.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
public void refreshProject(final IProject p) {
	Lock writeLock = instanceLock.writeLock();
	try{
		writeLock.lock();
		XdsProject xdsProject = getXdsProjectBy(p);
		if (xdsProject != null) {
			removeProjectFromModel(xdsProject);
		}
		xdsProject = new XdsProject(p, this);
		if (xdsProject != null) {
			addProjectToModel(xdsProject);
			expandNodes(xdsProject);
		}
	}
	finally {
		writeLock.unlock();
	}
}
 
Example 3
Source File: MemoryManager.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
public long saveDeferrals() {
	final Lock lock = m_allocationLock.writeLock();
   	lock.lock();
	try {
        assertOpen(); // BLZG-1658 MemoryManager should know when it has been closed
		if (m_deferredFreeOut.getBytesWritten() == 0) {
			return 0;
		}
		m_deferredFreeOut.writeInt(0); // terminate!
		final int outlen = m_deferredFreeOut.getBytesWritten();
		
		long addr = m_deferredFreeOut.save();
		
		addr <<= 32;
		addr += outlen;
		
		m_deferredFreeOut.reset();
		return addr;			
	} catch (IOException e) {
		throw new RuntimeException("Cannot write to deferred free", e);
	} finally {
		lock.unlock();
	}
}
 
Example 4
Source File: ReadWriteMap.java    From talent-aio with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** 
 * @see java.util.Map#clear()
 * 
 * @重写人: tanyaowu
 * @重写时间: 2017年2月8日 上午9:46:16
 * 
 */
@Override
public void clear()
{

	Lock lock = writeLock;
	try
	{
		lock.lock();
		map.clear();
	} catch (Exception e)
	{
		throw e;
	} finally
	{
		lock.unlock();
	}

}
 
Example 5
Source File: MPartition.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean checkAndPut(byte[] key,byte[] family,byte[] qualifier,byte[] expectedValue,DataPut put) throws IOException{
    Lock lock = getRowLock(key,0,key.length);
    lock.lock();
    try{
        DataResult latest=getLatest(key,family,null);
        if(latest!=null&& latest.size()>0){
            DataCell dc = latest.latestCell(family,qualifier);
            if(dc!=null){
                if(ByteComparisons.comparator().compare(dc.valueArray(),dc.valueOffset(),dc.valueLength(),expectedValue,0,expectedValue.length)==0){
                    put(put);
                    return true;
                }else return false;
            }else{
                put(put);
                return true;
            }
        }else{
            put(put);
            return true;
        }
    }finally{
        lock.unlock();
    }
}
 
Example 6
Source File: TaskWrapperManager.java    From Aria with Apache License 2.0 6 votes vote down vote up
/**
 * 从缓存中获取HTTP任务组的任务实体,如果任务实体不存在,则创建任务实体 获取{}
 *
 * @param taskId 任务ID
 * @return 地址列表为null或创建实体失败,返回null;成功返回{@link DGTaskWrapper}
 */
public <TW extends AbsTaskWrapper> TW getGroupWrapper(Class<TW> clazz, long taskId) {
  final Lock lock = this.lock;
  lock.lock();
  try {
    AbsTaskWrapper tWrapper = cache.get(convertKey(clazz, taskId));
    if (tWrapper == null || tWrapper.getClass() != clazz) {
      IGroupWrapperFactory factory = chooseGroupFactory(clazz);
      if (factory == null) {
        ALog.e(TAG, "任务实体创建失败");
        return null;
      }
      tWrapper = factory.getGroupWrapper(taskId);
      putTaskWrapper(tWrapper);
    }
    return (TW) tWrapper;
  } finally {
    lock.unlock();
  }
}
 
Example 7
Source File: TimetableSolver.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public DiscouragedInstructorBtbReport getDiscouragedInstructorBtbReport() {
	Lock lock = currentSolution().getLock().readLock();
	lock.lock();
	try {
		return new DiscouragedInstructorBtbReport(this);
	} finally {
		lock.unlock();
	}
}
 
Example 8
Source File: GlobalLockingTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testSingleVMLockUnlock() throws CacheException {
  String name = this.getUniqueName() + "-GLOBAL";
  Region region = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());

  Lock lock = region.getDistributedLock("obj");
  lock.lock();
  lock.unlock();
}
 
Example 9
Source File: SubsMapHelper.java    From vertx-hazelcast with Apache License 2.0 5 votes vote down vote up
public List<RegistrationInfo> get(String address) {
  Lock readLock = republishLock.readLock();
  readLock.lock();
  try {
    List<RegistrationInfo> list = new ArrayList<>();
    for (HazelcastRegistrationInfo registrationInfo : map.get(address)) {
      list.add(registrationInfo.unwrap());
    }
    return list;
  } finally {
    readLock.unlock();
  }
}
 
Example 10
Source File: HiveMQExtensions.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public void addHiveMQPlugin(final @NotNull HiveMQExtension extension) {
    checkNotNull(extension, "can only add valid extensions");

    final Lock lock = pluginsLock.writeLock();
    try {
        lock.lock();
        final HiveMQExtension oldPlugin = knownPlugins.get(extension.getId());
        if (oldPlugin != null) {
            extension.setPreviousVersion(oldPlugin.getVersion());
        }
        knownPlugins.put(extension.getId(), extension);
    } finally {
        lock.unlock();
    }
}
 
Example 11
Source File: ServiceQuene.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * 更新坐席当前服务中的用户状态,需要分布式锁
 * @param agentStatus
 * @param agentUser
 * @param orgi
 */
public synchronized static void updateAgentStatus(AgentStatus agentStatus , AgentUser agentUser , String orgi , boolean in){
	int users = getAgentUsers(agentStatus.getAgentno(), orgi) ;
	Lock lock = CacheHelper.getAgentStatusCacheBean().getLock("LOCK", orgi) ;
	lock.lock();
	try{
		agentStatus.setUsers(users);
		agentStatus.setUpdatetime(new Date());
		CacheHelper.getAgentStatusCacheBean().put(agentStatus.getAgentno(), agentStatus, orgi);
	}finally{
		lock.unlock();
	}
}
 
Example 12
Source File: ClientAuthenticatorsImpl.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
public @NotNull Map<String, EnhancedAuthenticator> getAuthenticatorMap() {
    final Lock lock = authenticatorLock.readLock();
    lock.lock();
    try {
        return ImmutableMap.copyOf(enhancedAuthenticatorMap);
    } finally {
        lock.unlock();
    }
}
 
Example 13
Source File: Caches.java    From kcache with Apache License 2.0 5 votes vote down vote up
@Override
public V getOrDefault(Object k, V defaultValue) {
    Lock lock = striped.get(k).readLock();
    lock.lock();
    try {
        return m.getOrDefault(k, defaultValue);
    } finally {
        lock.unlock();
    }
}
 
Example 14
Source File: TimetableSolver.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public org.unitime.timetable.gwt.shared.SuggestionsInterface.Suggestions computeSuggestions(SuggestionsContext context, ComputeSuggestionsRequest request) {
   	if (iWorking) return null;
   	Lock lock = currentSolution().getLock().writeLock();
	lock.lock();
	try {
		return ComputeSuggestionsBackend.computeSuggestions(context, this, request);
	} finally {
		lock.unlock();
	}
}
 
Example 15
Source File: ObligationService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds a collection of obligation handler to the list of registered handlers
 * 
 * This method waits until a write lock is obtained for the set of registered obligation handlers.
 * 
 * @param handlers the collection of handlers to add to the list of registered handlers.
 */
public void addObligationhandler(Collection<BaseObligationHandler> handlers) {
    if (handlers == null || handlers.isEmpty()) {
        return;
    }

    Lock writeLock = rwLock.writeLock();
    writeLock.lock();
    try {
        obligationHandlers.addAll(handlers);
    } finally {
        writeLock.unlock();
    }
}
 
Example 16
Source File: JdkHttpDownloader.java    From JMCCC with MIT License 4 votes vote down vote up
@Override
public <T> Future<T> download(DownloadTask<T> downloadTask, DownloadCallback<T> callback, int tries) {
	/*
	 * # Submit task
	 * ++++ read lock
	 * 	1. Has the shutdown flag been set? ................................................... read shutdown
	 * 		Yes - Reject execution.
	 * 		No - Go on.
	 * 
	 * 	2. Create a task handler, store it in tasks. ......................................... write tasks
	 * 
	 * 	3. Start the task handler. ........................................................... read executor
	 * ---- read unlock
	 */

	Objects.requireNonNull(downloadTask);
	if (tries < 1)
		throw new IllegalArgumentException("tries < 1");

	CallbackFutureTask<T> task = new CallbackFutureTask<>(new CallableDownloadTask<>(
			downloadTask,
			callback == null ? DownloadCallbacks.<T> empty() : callback,
			tries));

	Callback<T> statusCallback = Callbacks.whatever(new TaskInactiver(task));
	if (callback != null) {
		statusCallback = Callbacks.group(statusCallback, callback);
	}
	task.setCallback(callback);

	Lock lock = rwlock.readLock();
	lock.lock();
	try {
		if (shutdown)
			throw new RejectedExecutionException("The downloader has been shutdown.");

		tasks.add(task);
		executor.execute(task);
	} finally {
		lock.unlock();
	}

	return task;
}
 
Example 17
Source File: SingularityExecutorMonitor.java    From Singularity with Apache License 2.0 4 votes vote down vote up
public SubmitState submit(final SingularityExecutorTask task) {
  exitLock.lock();

  try {
    final Lock taskLock = task.getLock();
    taskLock.lock();
    try {
      if (runState == RunState.SHUTDOWN) {
        finishTask(
          task,
          TaskState.TASK_LOST,
          "Task couldn't start because executor is shutting down",
          Optional.<String>empty()
        );

        return SubmitState.REJECTED;
      }

      if (tasks.containsKey(task.getTaskId())) {
        return SubmitState.TASK_ALREADY_EXISTED;
      }
      tasks.put(task.getTaskId(), task);

      clearExitCheckerUnsafe();

      final ListenableFuture<ProcessBuilder> processBuildFuture = processBuilderPool.submit(
        task.getProcessBuilder()
      );

      processBuildingTasks.put(task.getTaskId(), processBuildFuture);

      watchProcessBuilder(task, processBuildFuture);
    } finally {
      taskLock.unlock();
    }
  } finally {
    exitLock.unlock();
  }

  return SubmitState.SUBMITTED;
}
 
Example 18
Source File: DataSynchronizer.java    From stitch-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Updates a single synchronized document by its given id with the given update description.
 *
 * @param nsConfig  the namespace synchronization config of the namespace where the document
 *                  lives.
 * @param documentId the _id of the document.
 * @param updateDescription the update description to apply locally.
 * @param atVersion the Stitch sync version that should be written locally for this update.
 * @param withHash the FNV-1a hash of the sanitized document.
 */
@CheckReturnValue
private LocalSyncWriteModelContainer updateOneFromRemote(
    final NamespaceSynchronizationConfig nsConfig,
    final BsonValue documentId,
    final UpdateDescription updateDescription,
    final BsonDocument atVersion,
    final long withHash
) {
  if (updateDescription.isEmpty()) {
    // don't do anything for completely no-op updates
    return null;
  }

  final UpdateDescription sanitizedUpdateDescription =
      sanitizeUpdateDescription(updateDescription);

  final MongoNamespace namespace = nsConfig.getNamespace();
  final ChangeEvent<BsonDocument> event;
  final Lock lock =
      this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock();
  lock.lock();
  final CoreDocumentSynchronizationConfig config;
  try {
    config = syncConfig.getSynchronizedDocument(namespace, documentId);
    if (config == null) {
      return null;
    }

    config.setPendingWritesComplete(withHash, atVersion);
  } finally {
    lock.unlock();
  }

  final LocalSyncWriteModelContainer container = newWriteModelContainer(nsConfig);

  // only emit the event and execute the local write if the
  // sanitized update description is non-empty
  if (!sanitizedUpdateDescription.isEmpty()) {
    container.addDocIDs(documentId);

    event = ChangeEvents.changeEventForLocalUpdate(
        namespace,
        documentId,
        sanitizedUpdateDescription,
        null,
        false
    );
    container.addLocalChangeEvent(event);

    // we should not upsert. if the document does not exist,
    // it means we are out of date on that document. we can
    // not apply an update change event as an upsert
    container.addLocalWrite(new UpdateOneModel<>(
        getDocumentIdFilter(documentId),
        sanitizedUpdateDescription.toUpdateDocument(),
        new UpdateOptions().upsert(false)
    ));
  }

  container.addConfigWrite(new ReplaceOneModel<>(
      CoreDocumentSynchronizationConfig.getDocFilter(namespace, config.getDocumentId()),
      config
  ));

  return container;
}
 
Example 19
Source File: UL_UNRELEASED_LOCK.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@DesireWarning("UL_UNRELEASED_LOCK")
void bug2(Lock any) {
    any.lock();
    // any code; might throw exception
    any.unlock();
}
 
Example 20
Source File: StorageDirect2.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public <A> void delete(long recid, Serializer<A> serializer) {
    final long ioRecid = IO_USER_START + recid*8;
    final Lock lock = locks[Utils.longHash(recid)%CONCURRENCY_FACTOR].writeLock();
    lock.lock();
    try{
        //get index val and zero it out
        final long indexVal = index.getLong(ioRecid);
        index.putLong(ioRecid,0L);

        long[] linkedRecords = null;
        int linkedPos = 0;
        if((indexVal&MASK_IS_LINKED)!=0){
            //record is composed of multiple linked records, so collect all of them
            linkedRecords = new long[2];

            //traverse linked records
            long linkedVal = phys.getLong(indexVal&MASK_OFFSET);
            for(;;){
                if(linkedPos==linkedRecords.length) //grow if necessary
                    linkedRecords = Arrays.copyOf(linkedRecords, linkedRecords.length*2);
                //store last linkedVal
                linkedRecords[linkedPos] = linkedVal;

                if((linkedVal&MASK_IS_LINKED)==0){
                    break; //this is last linked record, so break
                }
                //move and read to next
                linkedPos++;
                linkedVal = phys.getLong(linkedVal&MASK_OFFSET);
            }
        }

        //now lock everything and mark free space
        freeSpaceLock.lock();
        try{
            //free recid
            freeRecidPut(recid);
            //free first record pointed from indexVal
            freePhysPut(indexVal);

            //if there are more linked records, free those as well
            if(linkedRecords!=null){
                for(int i=0;i<linkedPos;i++){
                    freePhysPut(linkedRecords[i]);
                }
            }
        }finally {
            freeSpaceLock.unlock();
        }

    }finally{
        lock.unlock();
    }
}