kloop
kloop

Reputation: 4721

how to synchronize a group of threads?

I would like to make a synchronized method, such that all objects from that type of thread class can only access this function one at a time.

When looking at this web page, it says that:

An object for which access is to be coordinated is accessed through the use of synchronized methods. These methods are declared with the synchronized keyword. Only one synchronized method can be invoked for an object at a given point in time. This keeps synchronized methods in multiple threads from conflicting with each other.

This not what I am looking for, as I said, because I want to be able to make calls on the class mutually exclusive.

Upvotes: 0

Views: 806

Answers (3)

Gray
Gray

Reputation: 116888

Thought I'd provide some more information for posterity.

I want to be able to make calls on the class mutually exclusive.

So it depends on whether you are talking about a lock on an instance of the class or all instances of the class. When you are synchronizing on an object, other threads will block if they lock on the same object instance.

When an instance method is synchronized, it is if you are locking on this. The following are the same:

  public void synchronized foo() {
     ...
  }

Same as:

  public void foo() {
     synchronized (this) {
        ...
     }
  }

Typically, as @Tudor mentions, you should consider using a lock object instead of making methods synchronized. This allows you to lock around the specific lines you want to protect.

Any instance methods that are synchronized will block other calls to the same instance of the class. If you instead want to block all instances of a class, then you do what @JimN recommended and synchronize static methods. As he mentions, it's the same as synchronizing on the class object:

public static synchronized ReturnType methodName() {

If for some reason you need to lock across all objects then I'd wrap your lock in a singleton and write some lock/unlock methods using a ReentrantLock.

Upvotes: 0

Tudor
Tudor

Reputation: 62439

Use a static lock:

private final static Object lock = new Object();

public void foo() {
    synchronized(lock) {
        ...
    }
}

Upvotes: 0

JimN
JimN

Reputation: 3150

To make a method synchronize on the class (instead of a specific instance of the class), write:

public static synchronized ReturnType methodName() {
  ...
}

or

public static ReturnType methodName() {
  synchronized(ThisClass.class) {
    ...
  }
}

Upvotes: 1

Related Questions