Here's a few variations. If I understand the question right, I think you are looking for #5.
// 1. Static method
public static synchronized void doSomething() {
// Mutually exclusive for all calls
}
// 2. Static w/ Shared lock
private static Object STATIC_LOCK = new Object();
public static void staticMethod1() {
synchronized ( STATIC_LOCK ) {
// Mutually exclusive across staticMethod1() and staticMethod2()
}
}
public static void staticMethod2() {
synchronized ( STATIC_LOCK ) {
// Mutually exclusive across staticMethod1() and staticMethod2()
}
}
// 3. Instance method
public synchronized void doSomethingElse() {
// Mutually exclusive per instance of class
}
// 4. Instance w/ Shared lock
private Object lock = new Object();
public static void method1() {
synchronized ( lock ) {
// Mutually exclusive across method1() and method2() for each class instance
}
}
public static void method2() {
synchronized ( lock ) {
// Mutually exclusive across method1() and method2() for each class instance
}
}
// 5. Instance method synchronization across multiple class instances
private static Object SHARED_LOCK = new Object();
public void commonInstanceMethod() {
synchronized ( SHARED_LOCK ) {
// Mutually exclusive across all class instances
}
}