Java Code Examples for java.util.concurrent.locks.Lock#tryLock()
The following examples show how to use
java.util.concurrent.locks.Lock#tryLock() .
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: Basic.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriterView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriterView") { public void run() { if (gate != null ) toTheStartingGate(gate); Lock wl = sl.asWriteLock(); try { if (timeout < 0) wl.lockInterruptibly(); else wl.tryLock(timeout, unit); stamp(1L); // got the lock check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) wl.unlock(); } }}; }
Example 2
Source File: Basic.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
static Reader interruptibleReaderView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Reader("InterruptibleReaderView") { public void run() { if (gate != null ) toTheStartingGate(gate); final Lock rl = sl.asReadLock(); try { if (timeout < 0) rl.lockInterruptibly(); else rl.tryLock(timeout, unit); stamp(1L); // got the lock check(sl.isReadLocked()); check(!sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) rl.unlock(); } }}; }
Example 3
Source File: PersistenceUtil.java From java-unified-sdk with Apache License 2.0 | 6 votes |
public boolean deleteFile(File localFile) { if (null == localFile || !localFile.exists()) { return false; } boolean result = true; Lock writeLock = getLock(localFile.getAbsolutePath()).writeLock(); if (writeLock.tryLock()) { result = localFile.delete(); writeLock.unlock(); gLogger.d("succeed to obtain writeLock, and delete file: " + localFile.getAbsolutePath() + ", ret: " + result); } else { gLogger.w("failed to lock writeLocker, skip to delete file:" + localFile.getAbsolutePath()); result = false; } return result; }
Example 4
Source File: Basic.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriterView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriterView") { public void run() { if (gate != null ) toTheStartingGate(gate); Lock wl = sl.asWriteLock(); try { if (timeout < 0) wl.lockInterruptibly(); else wl.tryLock(timeout, unit); stamp(1L); // got the lock check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) wl.unlock(); } }}; }
Example 5
Source File: Basic.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriterView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriterView") { public void run() { if (gate != null ) toTheStartingGate(gate); Lock wl = sl.asWriteLock(); try { if (timeout < 0) wl.lockInterruptibly(); else wl.tryLock(timeout, unit); stamp(1L); // got the lock check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) wl.unlock(); } }}; }
Example 6
Source File: TryLock.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
public static void main(String args[]) throws Exception { ReentrantLock lock1 = new ReentrantLock(); ReadWriteLock rwLock = new ReentrantReadWriteLock(); Lock lock2 = rwLock.readLock(); Lock lock3 = rwLock.writeLock(); rwLock.readLock(); lock1.newCondition(); lock2.newCondition(); lock1.tryLock(); lock2.tryLock(); lock3.tryLock(); synchronized (lock1) { System.out.println("Howdy"); } }
Example 7
Source File: Basic.java From native-obfuscator with GNU General Public License v3.0 | 6 votes |
static Reader interruptibleReaderView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Reader("InterruptibleReaderView") { public void run() { if (gate != null ) toTheStartingGate(gate); final Lock rl = sl.asReadLock(); try { if (timeout < 0) rl.lockInterruptibly(); else rl.tryLock(timeout, unit); stamp(1L); // got the lock check(sl.isReadLocked()); check(!sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) rl.unlock(); } }}; }
Example 8
Source File: FileSystemView.java From jimfs with Apache License 2.0 | 6 votes |
/** * Acquires both write locks in a way that attempts to avoid the possibility of deadlock. Note * that typically (when only one file system instance is involved), both locks will be the same * lock and there will be no issue at all. */ private static void lockBoth(Lock sourceWriteLock, Lock destWriteLock) { while (true) { sourceWriteLock.lock(); if (destWriteLock.tryLock()) { return; } else { sourceWriteLock.unlock(); } destWriteLock.lock(); if (sourceWriteLock.tryLock()) { return; } else { destWriteLock.unlock(); } } }
Example 9
Source File: Basic.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriterView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriterView") { public void run() { if (gate != null ) toTheStartingGate(gate); Lock wl = sl.asWriteLock(); try { if (timeout < 0) wl.lockInterruptibly(); else wl.tryLock(timeout, unit); stamp(1L); // got the lock check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) wl.unlock(); } }}; }
Example 10
Source File: CounterMutation.java From stratio-cassandra with Apache License 2.0 | 6 votes |
private void grabCounterLocks(Keyspace keyspace, List<Lock> locks) throws WriteTimeoutException { long startTime = System.nanoTime(); for (Lock lock : LOCKS.bulkGet(getCounterLockKeys())) { long timeout = TimeUnit.MILLISECONDS.toNanos(getTimeout()) - (System.nanoTime() - startTime); try { if (!lock.tryLock(timeout, TimeUnit.NANOSECONDS)) throw new WriteTimeoutException(WriteType.COUNTER, consistency(), 0, consistency().blockFor(keyspace)); locks.add(lock); } catch (InterruptedException e) { throw new WriteTimeoutException(WriteType.COUNTER, consistency(), 0, consistency().blockFor(keyspace)); } } }
Example 11
Source File: LockTimeoutProviderImpl.java From p4ic4idea with Apache License 2.0 | 5 votes |
private final void tryLock(@NotNull Lock lock) throws InterruptedException { if (!lock.tryLock(getLockTimeout(), getLockTimeoutUnit())) { throw new InterruptedException("Timeout acquiring lock after " + getLockTimeout() + " " + getLockTimeoutUnit().toString().toLowerCase()); } }
Example 12
Source File: LockToken.java From consulo with Apache License 2.0 | 5 votes |
@Nullable public static LockToken attemptLock(@Nonnull Lock lock, long time) throws InterruptedException { if (lock.tryLock(time, TimeUnit.MILLISECONDS)) { return new LockToken(lock); } else { return null; } }
Example 13
Source File: BlockingCache.java From DBus with Apache License 2.0 | 5 votes |
private void acquireLock(Object key) { Lock lock = getLockForKey(key); if (timeout > 0) { try { boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS); if (!acquired) { throw new CacheException("Couldn't get a lock in " + timeout + " for the key " + key + " at the cache " + delegate.getId()); } } catch (InterruptedException e) { throw new CacheException("Got interrupted while trying to acquire lock for key " + key, e); } } else { lock.lock(); } }
Example 14
Source File: OperationUtils.java From twister2 with Apache License 2.0 | 5 votes |
/** * Progress the receivers and return true if needs further progress * * @param delegate the channel dataflow opeation * @param lock lock for final receiver * @param finalReceiver final receiver * @param partialLock lock for partial receiver * @param partialReceiver partial receiver * @return true if need further progress */ public static boolean progressReceivers(ChannelDataFlowOperation delegate, Lock lock, MessageReceiver finalReceiver, Lock partialLock, MessageReceiver partialReceiver) { boolean finalNeedsProgress = false; boolean partialNeedsProgress = false; try { delegate.progress(); if (lock.tryLock()) { try { finalNeedsProgress = finalReceiver.progress(); } finally { lock.unlock(); } } if (partialLock.tryLock()) { try { partialNeedsProgress = partialReceiver.progress(); } finally { partialLock.unlock(); } } } catch (Throwable t) { LOG.log(Level.SEVERE, "un-expected error", t); throw new Twister2RuntimeException(t); } return finalNeedsProgress || partialNeedsProgress; }
Example 15
Source File: ZkLeaderSelector.java From binlake with Apache License 2.0 | 5 votes |
@Override public void refreshLogPos() throws Exception { LogUtils.debug.debug("refreshLogPos"); Lock lock = this.lock; if (lock != null && lock.tryLock()) { // 如果成功落锁 try { IBinlogWorker worker = this.work; LogPosition logPos = null; MetaInfo metaInfo = this.metaInfo; if (worker != null && metaInfo != null && (logPos = worker.getLatestLogPosWithRm()) != null) { // 比较当前binlog 取最新的位置 try { if (binlogInfo.getWithGTID()) { // 如果开gtid 则比较gtid usingGTID(logPos); } } catch (Throwable exp) { // 如果有异常则 usingBinlogPos(logPos); } // 没有开gtid 则直接使用时间戳对比 if (!binlogInfo.getWithGTID()) { usingBinlogPos(logPos); } LogUtils.debug.debug(binlogInfo); // 打印最新 位置 long currWhen = binlogInfo.getBinlogWhen(); if (preWhen < currWhen) { updateBinlogInfo(Meta.BinlogInfo.marshalJson(this.binlogInfo)); preWhen = currWhen; } } } finally { lock.unlock(); } } }
Example 16
Source File: MemoryTransactionService.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
private static void tryLock(Session session, Lock lock, String lockType) { try { if(!lock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { throwTimeout(session, lockType); } } catch(InterruptedException e) { throw new QueryCanceledException(session); } }
Example 17
Source File: AbstractIndicatorsValveAlerter.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * Offer metric values in time windows. * * @param cacheKey * cacheKey address * @param value * metric value * @param gatherTime * gather time-stamp. * @param now * current date time-stamp. * @param ttl * time-to-live * @return */ protected List<MetricValue> offerTimeWindowQueue(String cacheKey, Double value, long gatherTime, long now, long ttl) { List<MetricValue> metricVals = emptyList(); // To solve the concurrency problem of metric window queue in // distributed environment. Lock lock = lockManager.getLock(getTimeWindowQueueCacheKey(cacheKey)); try { if (lock.tryLock(6L, TimeUnit.SECONDS)) { metricVals = ensureList(doPeekMetricValueQueue(cacheKey)); // Check & clean expired metrics. Iterator<MetricValue> it = metricVals.iterator(); while (it.hasNext()) { long gatherTime1 = it.next().getGatherTime(); // Remove expire data and repeat data if (abs(now - gatherTime1) >= ttl || gatherTime1 == gatherTime) { it.remove(); } } metricVals.add(new MetricValue(gatherTime, value)); // Offer to queue. doOfferMetricValueQueue(cacheKey, ttl, metricVals); } } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { lock.unlock(); } return metricVals; }
Example 18
Source File: OffHeapStorageArea.java From offheap-store with Apache License 2.0 | 4 votes |
public Collection<Page> release(Collection<Page> targets) { /* * TODO This locking might be too coarse grained - can we safely allow * threads in to the map while we do this release process? */ final Lock ownerLock = owner.writeLock(); if (thief || owner.isThief()) { if (!ownerLock.tryLock()) { return Collections.emptyList(); } } else { ownerLock.lock(); } try { Collection<Page> recovered = new LinkedList<>(); Collection<Page> freed = new LinkedList<>(); /* * iterate backwards from top, and free until top is beneath tail page. */ while (freed.size() < targets.size()) { long remove = allocator.getLastUsedPointer(); if (remove < 0) { for (int i = pages.size() - 1; i >= 0; i--) { Page free = pages.get(i); allocator.expand(-free.size()); pages.remove(i); if (targets.remove(free)) { recovered.add(free); } else { freed.add(free); } } validatePages(); break; } else { Collection<Page> releasedPages = new ArrayList<>(); released.push(releasedPages); try { if (!owner.evictAtAddress(remove, true).isEmpty() || moveAddressDown(remove)) { for (Page p : releasedPages) { if (targets.remove(p)) { recovered.add(p); } else { freed.add(p); } } validatePages(); } else if (releasedPages.isEmpty()) { break; } else { throw new AssertionError(); } } finally { released.pop(); } } } Iterator<Page> freePageSource = freed.iterator(); for (Page t : targets) { int index = getIndexForPage(t); if (index >= 0 && freePageSource.hasNext()) { Page f = freePageSource.next(); validate(!VALIDATING || f != t); validate(!VALIDATING || f.size() == t.size()); ((ByteBuffer) f.asByteBuffer().clear()).put((ByteBuffer) t.asByteBuffer().clear()); pages.put(index, f); recovered.add(t); } } validatePages(); while (freePageSource.hasNext()) { freePage(freePageSource.next()); } return recovered; } finally { ownerLock.unlock(); } }
Example 19
Source File: SnapshotFileCache.java From hbase with Apache License 2.0 | 4 votes |
/** * Check to see if any of the passed file names is contained in any of the snapshots. First checks * an in-memory cache of the files to keep. If its not in the cache, then the cache is refreshed * and the cache checked again for that file. This ensures that we never return files that exist. * <p> * Note this may lead to periodic false positives for the file being referenced. Periodically, the * cache is refreshed even if there are no requests to ensure that the false negatives get removed * eventually. For instance, suppose you have a file in the snapshot and it gets loaded into the * cache. Then at some point later that snapshot is deleted. If the cache has not been refreshed * at that point, cache will still think the file system contains that file and return * <tt>true</tt>, even if it is no longer present (false positive). However, if the file never was * on the filesystem, we will never find it and always return <tt>false</tt>. * @param files file to check, NOTE: Relies that files are loaded from hdfs before method is * called (NOT LAZY) * @return <tt>unReferencedFiles</tt> the collection of files that do not have snapshot references * @throws IOException if there is an unexpected error reaching the filesystem. */ // XXX this is inefficient to synchronize on the method, when what we really need to guard against // is an illegal access to the cache. Really we could do a mutex-guarded pointer swap on the // cache, but that seems overkill at the moment and isn't necessarily a bottleneck. public synchronized Iterable<FileStatus> getUnreferencedFiles(Iterable<FileStatus> files, final SnapshotManager snapshotManager) throws IOException { List<FileStatus> unReferencedFiles = Lists.newArrayList(); List<String> snapshotsInProgress = null; boolean refreshed = false; Lock lock = null; if (snapshotManager != null) { lock = snapshotManager.getTakingSnapshotLock().writeLock(); } if (lock == null || lock.tryLock()) { try { if (snapshotManager != null && snapshotManager.isTakingAnySnapshot()) { LOG.warn("Not checking unreferenced files since snapshot is running, it will " + "skip to clean the HFiles this time"); return unReferencedFiles; } for (FileStatus file : files) { String fileName = file.getPath().getName(); if (!refreshed && !cache.contains(fileName)) { refreshCache(); refreshed = true; } if (cache.contains(fileName)) { continue; } if (snapshotsInProgress == null) { snapshotsInProgress = getSnapshotsInProgress(); } if (snapshotsInProgress.contains(fileName)) { continue; } unReferencedFiles.add(file); } } finally { if (lock != null) { lock.unlock(); } } } return unReferencedFiles; }
Example 20
Source File: DistributedRegion.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
/** * If this region's scope is GLOBAL, get a distributed lock on the given key, * and return the Lock. The sender is responsible for unlocking. * * @return the acquired Lock if the region is GLOBAL, otherwise null. * * @throws NullPointerException * if key is null */ private Lock getDistributedLockIfGlobal(Object key) throws TimeoutException { if (getScope().isGlobal()) { if (isLockingSuspendedByCurrentThread()) return null; long start = System.currentTimeMillis(); long timeLeft = getCache().getLockTimeout(); long lockTimeout = timeLeft; StringId msg = null; Object[] msgArgs = null; while (timeLeft > 0 || lockTimeout == -1) { this.cache.getCancelCriterion().checkCancelInProgress(null); boolean interrupted = Thread.interrupted(); try { Lock dlock = getDistributedLock(key); if (!dlock.tryLock(timeLeft, TimeUnit.SECONDS)) { msg = LocalizedStrings.DistributedRegion_ATTEMPT_TO_ACQUIRE_DISTRIBUTED_LOCK_FOR_0_FAILED_AFTER_WAITING_1_SECONDS; msgArgs = new Object[] {key, Long.valueOf((System.currentTimeMillis() - start) / 1000L)}; break; } return dlock; } catch (InterruptedException ex) { interrupted = true; this.cache.getCancelCriterion().checkCancelInProgress(ex); // FIXME Why is it OK to keep going? if (lockTimeout > -1) { timeLeft = getCache().getLockTimeout() - ((System.currentTimeMillis() - start) / 1000L); } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // while if (msg == null) { msg = LocalizedStrings.DistributedRegion_TIMED_OUT_AFTER_WAITING_0_SECONDS_FOR_THE_DISTRIBUTED_LOCK_FOR_1; msgArgs = new Object[] {Integer.valueOf(getCache().getLockTimeout()), key}; } throw new TimeoutException(msg.toLocalizedString(msgArgs)); } else { return null; } }