Can someone please explain how synchronization obtains lock on an Object?

I have a code in which I want to obtain a lock on the String value dynamically.

for e.g.

String a = "abc";
synchronization(a){
   //some logic
}

Now what I want is if from an api I receive value of a abc from one request and on the other request I receive value of a as abc while obtaining lock on the previous request, the new request should wait on the basis of value.

Can someone please help how it works/ how can I achieve this?

1 Answers

2
T.J. Crowder On

Now what I want is if from an api I receive value of a abc from one request and on the other request I receive value of a as abc while obtaining lock on the previous request, the new request should wait on the basis of value.

To use synchronized for this, you'd need to ensure that the "abc" objects were the same string object, not just equivalent strings (for the same reason you don't compare strings with ==), by using intern.

synchronized (a.intern()) {
    // ...
}

synchronized requires the same object, not just equivalent ones.


That said, synchronizing on string objects to prevent two parts of your app handling equivalent requests at the same time seems (from the outside, without details) a bit odd, not least because it won't scale beyond a single JVM instance.