Question

Is there such thing as a "non-blocking lock" in Java? By that, I mean is there a way to retain the properties of synchronization (atomic protection and memory visibility - the latter can come later, BUT the first is the most important thing I'm looking for right now) but also have multiple threads not have to wait for the monitor of the object?

What I'm looking for - just to be clear - is not CAS operations, but an implementation of, say, the synchronized keyword, or ReentrantLock that works like a Semaphore BUT with actual synchronization semantics that doesn't block threads to perform a certain action like invocations getters and setters.

Was it helpful?

Solution 3

As with the responses in all of the answers and OP, I conclude that this isn't possible with current synchronization techniques. I will conclude by saying that we cannot perform atomic compound operations using a get/set style method call without using blocking synchronizers.

If contention is the problem, I suggest reading this article. A quick google search should turn up some other links if you are digging deeper.

OTHER TIPS

You can look at lock-striping techniques (used in concurrenthashmap )to see if it meets your needs. Their basic idea is that you break your structure into segments and if a thread is modifying one segment , you can still read from the other segments.

You can also try the CopyOnWriteArrayList where if you are modfying an array, you create a copy and use it for any read operations while the array is being modified. The problem here is you are not guaranteed to get the latest update to the data

Both the above approaches are for building concurrent systems instead of synchronized systems.

I can't think of anything built in.

But you could use tryLock to determine if you can acquire a Lock and perform a synchronized action or, if you cannot acquire the Lock, perform a non-synchronized action.

Lock l = ...

if(l.tryLock()) {
    try {
        // do your synchronized action
    } finally {
        l.unlock();
    }
} else {
    // welp, we couldn't get the lock.
    // do some local work.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top