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

The following examples show how to use java.util.concurrent.locks.Lock#lock() . 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: MemTxnStore.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean keepAlive(long txnId) throws IOException{
    Lock writeLock=lockStriper.get(txnId).writeLock();
    writeLock.lock();
    try{
        TxnHolder holder=txnMap.get(txnId);
        if(holder==null) return false;

        Txn txn=holder.txn;
        if(txn.getState()!=Txn.State.ACTIVE)
            return false; //don't keep keepAlives going if the transaction is finished
        if(isTimedOut(holder))
            throw new MTransactionTimeout(txnId);

        holder.keepAliveTs=clock.currentTimeMillis();
        return true;
    }finally{
        writeLock.unlock();
    }
}
 
Example 2
Source File: TimetableSolver.java    From unitime with Apache License 2.0 6 votes vote down vote up
@Override
  public AssignmentPreferenceInfo getAssignmentInfo(Long classId) {
  	Lock lock = currentSolution().getLock().readLock();
lock.lock();
try {
  		Lecture lecture = null;
  		for (Lecture l: currentSolution().getModel().variables()) {
  			if (l.getClassId().equals(classId)) {
  				lecture = l; break;
  			}
  		}
  		if (lecture==null) return null;
  		Placement placement = (Placement)currentSolution().getAssignment().getValue(lecture);
  		if (placement==null) return null;
  		return new AssignmentPreferenceInfo(this,placement);
  	} finally {
  		lock.unlock();
  	}
  }
 
Example 3
Source File: IQDiscoInfoHandler.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private void restoreCacheContent() {
    for (String feature : localServerFeatures) {
        Lock lock = CacheFactory.getLock(feature, serverFeatures);
        try {
            lock.lock();
            HashSet<NodeID> nodeIDs = serverFeatures.get(feature);
            if (nodeIDs == null) {
                nodeIDs = new HashSet<>();
            }
            nodeIDs.add(XMPPServer.getInstance().getNodeID());
            serverFeatures.put(feature, nodeIDs);
        }
        finally {
            lock.unlock();
        }
    }
}
 
Example 4
Source File: InMemoryPubSubPersistenceProvider.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public List<PublishedItem> getPublishedItems( LeafNode node )
{
    log.debug( "Getting published items for node {}", node.getUniqueIdentifier() );
    List<PublishedItem> publishedItems;
    final Lock lock = itemsCache.getLock( node.getUniqueIdentifier() );
    lock.lock();
    try {
        final List<PublishedItem> items = itemsCache.get( node.getUniqueIdentifier() );
        publishedItems = items != null ? items : new ArrayList<>();
    } finally {
        lock.unlock();
    }

    return publishedItems;
}
 
Example 5
Source File: MemoryManager.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void activateTx() {
	final Lock lock = m_allocationLock.writeLock();
	lock.lock();
    try {
        assertOpen(); // BLZG-1658 MemoryManager should know when it has been closed
        m_activeTxCount++;
        if(log.isInfoEnabled())
            log.info("#activeTx="+m_activeTxCount);
        
        // check for new session protection
        if (m_activeTxCount == 1 && m_contexts.isEmpty()) {
        	acquireSessions();
        }
    } finally {
    	lock.unlock();
    }
}
 
Example 6
Source File: StorageDirect2.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <A> void update(long recid, A value, Serializer<A> serializer) {
    final Lock lock = locks[Utils.longHash(recid)%CONCURRENCY_FACTOR].writeLock();
    lock.lock();
    try{


    }finally{
        lock.unlock();
    }
}
 
Example 7
Source File: PaxosState.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static PrepareResponse prepare(Commit toPrepare)
{
    long start = System.nanoTime();
    try
    {
        Lock lock = LOCKS.get(toPrepare.key);
        lock.lock();
        try
        {
            PaxosState state = SystemKeyspace.loadPaxosState(toPrepare.key, toPrepare.update.metadata());
            if (toPrepare.isAfter(state.promised))
            {
                Tracing.trace("Promising ballot {}", toPrepare.ballot);
                SystemKeyspace.savePaxosPromise(toPrepare);
                return new PrepareResponse(true, state.accepted, state.mostRecentCommit);
            }
            else
            {
                Tracing.trace("Promise rejected; {} is not sufficiently newer than {}", toPrepare, state.promised);
                // return the currently promised ballot (not the last accepted one) so the coordinator can make sure it uses newer ballot next time (#5667)
                return new PrepareResponse(false, state.promised, state.mostRecentCommit);
            }
        }
        finally
        {
            lock.unlock();
        }
    }
    finally
    {
        Keyspace.open(toPrepare.update.metadata().ksName).getColumnFamilyStore(toPrepare.update.metadata().cfId).metric.casPrepare.addNano(System.nanoTime() - start);
    }

}
 
Example 8
Source File: Caches.java    From kcache with Apache License 2.0 5 votes vote down vote up
public V put(K key, V value) {
    Lock lock = striped.get(key).writeLock();
    lock.lock();
    try {
        return m.put(key, value);
    } finally {
        lock.unlock();
    }
}
 
Example 9
Source File: RocksRawKVStore.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
CompletableFuture<Void> writeSstSnapshot(final String snapshotPath, final Region region, final ExecutorService executor) {
    final Timer.Context timeCtx = getTimeContext("WRITE_SST_SNAPSHOT");
    final Lock readLock = this.readWriteLock.readLock();
    readLock.lock();
    try {
        final String tempPath = snapshotPath + "_temp";
        final File tempFile = new File(tempPath);
        FileUtils.deleteDirectory(tempFile);
        FileUtils.forceMkdir(tempFile);

        final EnumMap<SstColumnFamily, File> sstFileTable = getSstFileTable(tempPath);
        final CompletableFuture<Void> snapshotFuture = new CompletableFuture<>();
        final CompletableFuture<Void> sstFuture = createSstFiles(sstFileTable, region.getStartKey(),
            region.getEndKey(), executor);
        sstFuture.whenComplete((aVoid, throwable) -> {
            if (throwable == null) {
                try {
                    final File snapshotFile = new File(snapshotPath);
                    FileUtils.deleteDirectory(snapshotFile);
                    if (!tempFile.renameTo(snapshotFile)) {
                        throw new StorageException("Fail to rename [" + tempPath + "] to [" + snapshotPath + "].");
                    }
                    snapshotFuture.complete(null);
                } catch (final Throwable t) {
                    snapshotFuture.completeExceptionally(t);
                }
            } else {
                snapshotFuture.completeExceptionally(throwable);
            }
        });
        return snapshotFuture;
    } catch (final Exception e) {
        throw new StorageException("Fail to do read sst snapshot at path: " + snapshotPath, e);
    } finally {
        readLock.unlock();
        timeCtx.stop();
    }
}
 
Example 10
Source File: XdsModel.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public void putNonWorkspaceXdsElement(IFileStore sourceFile,
   		IXdsElement xdsElement) {
   	Lock writeLock = instanceLock.writeLock();
   	try{
   		writeLock.lock();
   		location2XdsElement.put(new PathWithLocationType(sourceFile) , xdsElement);
   	}
   	finally {
   		writeLock.unlock();
   	}
}
 
Example 11
Source File: SeedArrayGenerationPerformance.java    From commons-rng with Apache License 2.0 5 votes vote down vote up
/**
 * Get the next {@code long} from the RNG. The lock is used to guard access to the generator.
 *
 * @param lock Lock guarding access to the generator.
 * @param rng Random generator.
 * @return the long
 */
private static long nextLong(Lock lock, UniformRandomProvider rng) {
    lock.lock();
    try {
        return rng.nextLong();
    } finally {
        lock.unlock();
    }
}
 
Example 12
Source File: HALogWriter.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isHALogOpen() {
       
       final Lock lock = m_stateLock.readLock();
       lock.lock();
       try {
           return m_state != null && !m_state.isCommitted();
       } finally {
           lock.unlock();
       }
    
}
 
Example 13
Source File: IndexingStamp.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void update(int fileId, @Nonnull ID<?, ?> indexName, final long indexCreationStamp) {
  if (fileId < 0 || fileId == INVALID_FILE_ID) return;
  Lock writeLock = getStripedLock(fileId).writeLock();
  writeLock.lock();
  try {
    Timestamps stamp = createOrGetTimeStamp(fileId);
    if (stamp != null) stamp.set(indexName, indexCreationStamp);
  }
  finally {
    writeLock.unlock();
  }
}
 
Example 14
Source File: Caches.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
@Override
public <A> void delete(long recid, Serializer<A> serializer){
    Engine engine = getWrappedEngine();
    LongMap items2 = checkClosed(items);

    final Lock lock  = locks[Store.lockPos(recid)];
    lock.lock();
    try{
        items2.remove(recid);
        engine.delete(recid,serializer);
    }finally {
        lock.unlock();
    }

}
 
Example 15
Source File: LocalDistributor.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Beta
public void refresh() {
  Lock writeLock = lock.writeLock();
  writeLock.lock();
  try {
    hosts.forEach(Host::runHealthCheck);
  } finally {
    writeLock.unlock();
  }
}
 
Example 16
Source File: MemoryManager.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ByteBuffer[] get(final long addr) {

	if (addr == 0L)
		throw new IllegalArgumentException();
	
	final int rwaddr = getAllocationAddress(addr);
	final int size = getAllocationSize(addr);

	if (size <= 0)
		throw new IllegalArgumentException();

	// BLZG-1658 We need at least a readLock() on the allocation lock to protect against a concurrent close().
       final Lock lock = m_allocationLock.readLock();
   	lock.lock();
	try {
		assertOpen(); // BLZG-1658 MemoryManager should know when it has
						// been closed

		if (size <= SectorAllocator.BLOB_SIZE) {

			/*
			 * This is a simple allocation.
			 */

			return new ByteBuffer[] { getBuffer(rwaddr, size) };

		} else {

			/*
			 * This will be a BLOB, so retrieve the header, then parse to
			 * retrieve components and assign to ByteBuffer[].
			 */

			final ByteBuffer[] hdrbuf = getBlobHdr(addr);
			int hdrIndex = 0;
			final int nblocks = hdrbuf[hdrIndex].getInt();

			final ByteBuffer[] blobbufs = new ByteBuffer[nblocks];
			int remaining = size;
			for (int i = 0; i < nblocks; i++) {
				if (hdrbuf[hdrIndex].remaining() == 0) {
					hdrIndex++;
				}
				int blockSize = remaining <= SectorAllocator.BLOB_SIZE ? remaining
						: SectorAllocator.BLOB_SIZE;
				blobbufs[i] = getBuffer(hdrbuf[hdrIndex].getInt(), blockSize);

				remaining -= blockSize;
			}

			return blobbufs;
		}
	} finally {
       	lock.unlock();
       }
}
 
Example 17
Source File: TopicTreeImpl.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean addTopic(@NotNull final String subscriber, @NotNull final Topic topic, final byte flags, @Nullable final String sharedGroup) {

    checkNotNull(subscriber, "Subscriber must not be null");
    checkNotNull(topic, "Topic must not be null");

    final String[] contents = StringUtils.splitPreserveAllTokens(topic.getTopic(), '/');

    //Do not store subscriptions with more than 1000 segments
    if (contents.length > 1000) {
        log.warn("Subscription from {} on topic {} exceeds maximum segment count of 1000 segments, ignoring it", subscriber, topic);
        return false;
    }

    if (contents.length == 0) {
        log.debug("Tried to add an empty topic to the topic tree.");
        return false;
    }

    final SubscriberWithQoS entry = new SubscriberWithQoS(subscriber, topic.getQoS().getQosNumber(), flags, sharedGroup, topic.getSubscriptionIdentifier(), null);
    if (contents.length == 1 && contents[0].equals("#")) {
        if (!rootWildcardSubscribers.contains(entry)) {
            //Remove the same subscription with different QoS
            final boolean removed = removeRootWildcardSubscriber(subscriber, sharedGroup);
            final boolean added = rootWildcardSubscribers.add(entry);
            if (added) {
                subscriptionCounter.inc();
            }
            return removed;
        }
        return true;
    }

    final String segmentKey = contents[0];

    final Lock lock = segmentLocks.get(segmentKey).writeLock();

    lock.lock();
    try {

        SegmentRootNode node = segments.get(segmentKey);
        if (node == null) {
            node = new SegmentRootNode(segmentKey, mapCreationThreshold, mapCreationThreshold, subscriptionCounter);
            segments.put(segmentKey, node);
        }

        if (contents.length == 1) {
            return node.addExactSubscriber(entry);
        } else {

            return addNode(entry, contents, node, 1);
        }
    } finally {
        lock.unlock();
    }
}
 
Example 18
Source File: ThingManagerImpl.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void thingUpdated(final Thing thing, ThingTrackerEvent thingTrackerEvent) {
    ThingUID thingUID = thing.getUID();
    if (thingUpdatedLock.contains(thingUID)) {
        // called from the thing handler itself, therefore
        // it exists, is initializing/initialized and
        // must not be informed (in order to prevent infinite loops)
        replaceThing(getThing(thingUID), thing);
    } else {
        Lock lock1 = getLockForThing(thing.getUID());
        try {
            lock1.lock();
            Thing oldThing = getThing(thingUID);
            ThingHandler thingHandler = replaceThing(oldThing, thing);
            if (thingHandler != null) {
                if (ThingHandlerHelper.isHandlerInitialized(thing) || isInitializing(thing)) {
                    if (oldThing != null) {
                        oldThing.setHandler(null);
                    }
                    thing.setHandler(thingHandler);
                    safeCaller.create(thingHandler, ThingHandler.class).build().thingUpdated(thing);
                } else {
                    logger.debug(
                            "Cannot notify handler about updated thing '{}', because handler is not initialized (thing must be in status UNKNOWN, ONLINE or OFFLINE).",
                            thing.getThingTypeUID());
                    if (thingHandler.getThing() == thing) {
                        logger.debug("Initializing handler of thing '{}'", thing.getThingTypeUID());
                        if (oldThing != null) {
                            oldThing.setHandler(null);
                        }
                        thing.setHandler(thingHandler);
                        initializeHandler(thing);
                    } else {
                        logger.debug("Replacing uninitialized handler for updated thing '{}'",
                                thing.getThingTypeUID());
                        ThingHandlerFactory thingHandlerFactory = getThingHandlerFactory(thing);
                        unregisterHandler(thingHandler.getThing(), thingHandlerFactory);
                        registerAndInitializeHandler(thing, thingHandlerFactory);
                    }
                }
            } else {
                registerAndInitializeHandler(thing, getThingHandlerFactory(thing));
            }
        } finally {
            lock1.unlock();
        }
    }
}
 
Example 19
Source File: WORMStrategy.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Read on the backing file. {@link ByteBuffer#remaining()} bytes will be
 * read into the caller's buffer, starting at the specified offset in the
 * backing file.
 * 
 * @param offset
 *            The offset of the first byte (now absolute, not relative to the 
 *            start of the data region).
 * @param dst
 *            Where to put the data. Bytes will be written at position until
 *            limit.
 *            
 * @return The caller's buffer, prepared for reading.
 */
public ByteBuffer readRaw(final long offset, final ByteBuffer dst) {

    final Lock readLock = extensionLock.readLock();
    readLock.lock();
    try {
        final int startPos = dst.position();
        try {

            // the offset into the disk file.
            // final long pos = headerSize + offset;
            final long pos = offset; // offset is physical disk address

            // read on the disk.
            final int ndiskRead = FileChannelUtility.readAll(opener, dst,
                    pos);

            // update performance counters.
            final StoreCounters<?> c = (StoreCounters<?>) storeCounters
                    .get().acquire();
            try {
                c.ndiskRead += ndiskRead;
            } finally {
                c.release();
            }

        } catch (IOException ex) {

            throw new RuntimeException(ex);

        }

        // Reset start position - do not flip()
        dst.position(startPos);

        return dst;
    } finally {

        readLock.unlock();
    }

}
 
Example 20
Source File: AsyncChannelTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Test that client channel works in async mode.
 */
@Test
public void testAsyncRequests() throws Exception {
    try (IgniteClient client = startClient(0)) {
        Ignite ignite = grid(0);

        IgniteCache<Integer, Integer> igniteCache = ignite.cache(CACHE_NAME);
        ClientCache<Integer, Integer> clientCache = client.cache(CACHE_NAME);

        clientCache.clear();

        Lock keyLock = igniteCache.lock(0);

        IgniteInternalFuture fut;

        keyLock.lock();

        try {
            CountDownLatch latch = new CountDownLatch(1);

            fut = GridTestUtils.runAsync(() -> {
                latch.countDown();

                // This request is blocked until we explicitly unlock key in another thread.
                clientCache.put(0, 0);

                clientCache.put(1, 1);

                assertEquals(10, clientCache.size(CachePeekMode.PRIMARY));
            });

            latch.await();

            for (int i = 2; i < 10; i++) {
                clientCache.put(i, i);

                assertEquals((Integer)i, igniteCache.get(i));
                assertEquals((Integer)i, clientCache.get(i));
            }

            // Parallel thread must be blocked on key 0.
            assertFalse(clientCache.containsKey(1));
        }
        finally {
            keyLock.unlock();
        }

        fut.get();

        assertTrue(clientCache.containsKey(1));
    }
}