Guillaume Delafosse
Guillaume Delafosse

Reputation: 242

Is Guava Striped.get(key) synchronized?

I'm concerned if the Guava Striped.get(key) method synchronized.

So is this class thread safe?

class UrlLocker  {
    Striped<Lock> locks = Striped.lazyWeakLock(1);

    public void lock(Url url) {
        locks.get(url).lock();
    }

    public void unlock(Url url) {
        locks.get(url).unlock();
    }
}

Or do I need to synchronize my method to protect accessing the locks map?

Upvotes: 0

Views: 901

Answers (2)

Guillaume Delafosse
Guillaume Delafosse

Reputation: 242

Diving into guava MapMaker implementation, I see that the magic is in the method com.google.common.collect.ComputingConcurrentHashMap.ComputingSegment#getOrCompu‌​te which protect the critical section where the Lock is computed and put in the Map.

Upvotes: 0

Petro Semeniuk
Petro Semeniuk

Reputation: 7038

To make it completely thread safe you would need to declare locks instance as final:

class UrlLocker  {
    final Striped<Lock> locks = Striped.lazyWeakLock(1);

    public void lock(Url url) {
        locks.get(url).lock();
    }

    public void unlock(Url url) {
        locks.get(url).unlock();
    }
}

Also, correctness of your code depends on #hashcode implementation of Url class itself. If you would use java.net.URL (it doesn't look like you do) hashcode would change if you'd loose internet connection of if DNS resolution would change between calls.

Extract from Striped javadoc:

...assuming {@link Object#hashCode()} is correctly implemented for the keys...

Upvotes: 1

Related Questions