Imagine a scenario where we need to lock based on the device id, which is a string. Many people recommend using String.intern()
as the lock object, but some people recommend using Striped
for concurrency control, such as the following code:
import com.google.common.util.concurrent.Striped;
import java.util.concurrent.locks.Lock;
public class Test {
private Striped<Lock> striped = Striped.lock(8);
public void businessLogicByStringIntern(String deviceId) {
// use deviceId.intern() as lock
synchronized (deviceId.intern()) {
// execute code thread-safely
}
}
public void businessLogicByStriped(String deviceId) {
// use striped lock
synchronized (striped.get(deviceId)) {
// execute code thread-safely
}
}
}
Which implementation is more recommended, businessLogicByStringIntern
or businessLogicByStriped
?
Reference:
Striped (Guava: Google Core Libraries for Java 19.0 API)