In principle, you can synchronize on any object in Java. It's not in itself "not correct" to synchronize on a String
object; it depends on what exactly you're doing.
But if userId
is a local variable in a method, then this is not going to work. Each thread that executes the method with have its own copy of the variable (presumably referring to a different String
object for each thread); synchronizing between threads ofcourse only works when you make multiple threads synchronize on the same object.
You'd have to make the object you're synchronizing on a member variable of the object that contains the method in which you have the synchronized
block. If multiple threads are then calling the method on the same object, you'll achieve mutual exclusivity.
class Something {
private Object lock = new Object();
public void someMethod() {
synchronized (lock) {
// ...
}
}
}
You could also use explicit locks from the java.util.concurrent.locks
package, that can give you more control if you need that:
class Something {
private Lock lock = new ReentrantLock();
public void someMethod() {
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
}
}
Especially if you want an exclusive lock for writing, but you don't want threads to have to wait for each other when reading, you might want to use a ReadWriteLock
.