We are using stripe lock for one of our implementation. We take readlock on some final constant and a writelock on key. We noticed that we ran into a deadlock because hash code of two different keys turned out to be same. And hence it is like upgrading a read lock to write lock and we ran into deadlock. Below is the code used by Stripe library to generate a hashcode. What is the best way to handle this deadlock?
Stripe code:
static int smear(int hashCode)
{
hashCode ^= hashCode >>> 20 ^ hashCode >>> 12;
return hashCode ^ hashCode >>> 7 ^ hashCode >>> 4;
}
static final int indexFor(Object key)
{
int hash = smear(key.hashCode());
int mask = ceilToPowerOfTwo(2003) -1;
return hash & mask;
}
static int ceilToPowerOfTwo(int x)
{
return 1 << IntMath.log2(x, RoundingMode.CEILING);
}
public static void main(String[] args) {
String publicKey = "$public";
int hash = indexFor(publicKey );
for(int i=0;i<1000;i++) {
String key = "key"+i;
if(indexFor(key) == hash) {
System.out.println("Hash of "+key + " is same as hash of public");
}
}
}
Our Logic:
Take readLock on publicKey
Take writeLock on key
release the write lock
release the read lock