'When String is the object of the lock, which is better String.intern() or Striped?

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)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source