Hi. I have a class like this:
public class Utils {
public static void doSomething() {
// doSomething code
}
public static void doSomethingElse() {
// doSomethingElse code
}
}
I want the two methods to be synchronized but not synchronized against each other i.e. no two threads can process the doSomething() method at the same time, no two threads can process doSomethingElse() at the same time but it is OK for a thread to process the doSomething() method and another to process the doSomethingElse() method at the same time.
I've implemented something like this:
public class Utils {
private static final String DO_SOMETHING_LOCK = "DO_SOMETHING_LOCK";
private static final String DO_SOMETHING_ELSE_LOCK = "DO_SOMETHING_ELSE_LOCK";
public static void doSomething() {
synchronized(DO_SOMETHING_LOCK) {
// doSomething code
}
}
public static void doSomethingElse() {
synchronized(DO_SOMETHING_ELSE_LOCK) {
// doSomethingElse code
}
}
I see the Scott Stanchfield response uses a similar approach here:
http://stackoverflow.com/questions/578904/how-do-synchronized-static-methods-work-in-java
but is this the best way to do this? It seems kind of clunky to me, creating two objects, only to be used for locking - is there a better way to do this?