-1

I have a method which can be accessed by one thread at a time. Even if threads use different objects, only one thread should access the method at a time.

What can I use in Java do achieve this? I think 'synchronized' keyword will allow multiple threads at a time to access the method if they use different objects. The same with Re-entrant locks I believe.

hars
  • 127
  • 4
  • 17
  • You lock on a shared object, e.g. use a `ReentrantLock` stored in a `static` field, or use `synchronized` on an `Object` stored in a `static` field. – Andreas Oct 20 '17 at 20:38

1 Answers1

1

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
    }
}
Matt MacLean
  • 19,410
  • 7
  • 50
  • 53
  • I am using the first now, since only one thread can access it, regardless of how many objects it has. – hars Oct 20 '17 at 22:34
  • @hars: #1 and #5 are essentially the same thing. – Jim Mischel Oct 20 '17 at 23:51
  • In #1, I saw using 'static synchronized method' meant that I have to use static contents inside method which is a problem. So I started using #5 which is a pretty good way to do things. No other changes are required when using this. – hars Oct 23 '17 at 17:21