Skip to content

Instantly share code, notes, and snippets.

// N.B. Draining the queue is only necessary to ensure that we don't accumulate empty references
// in the array. We could skip this if we decide we don't care about holding on to Reference
// objects indefinitely.
private void drainQueue() {
Reference<? extends L> ref;
while ((ref = queue.poll()) != null) {
// We only ever register ArrayReferences with the queue so this is always safe.
ArrayReference<? extends L> arrayRef = (ArrayReference<? extends L>) ref;
// Try to clear out the array slot, n.b. if we fail that is fine, in either case the
// arrayRef will be out of the array after this step.
@Override final int indexFor(Object key) {
int hash = smear(key.hashCode());
return hash & mask;
}
/*
* This method was written by Doug Lea with assistance from members of JCP
* JSR-166 Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*
@nipuns
nipuns / gist:44eab74add31487044e6
Created April 4, 2015 17:10
Locker with Striped
public class Locker {
private static final Striped<Lock> sLock = Striped.lazyWeakLock(100);
public static Lock getLock(String lockId) {
return sLock.get(lockId);
}
}
package com.nipunsaggar.locker;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
public class Locker {
private static final Map <String, ReentrantLock> sLockStore = new ConcurrentHashMap<>();
private static LockPool sLockPool = new LockPool();
/**
* Usage:
* Lock lock = Locker.getLock();
* try {
* lock.lock();
* //do something
* } finally {
* lock.unlock();
* }
}