Gokul Kulkarni
Gokul Kulkarni

Reputation: 2239

Java methods thread safe

I have a scenario, searched quite a bit, but did not get satisfactory answer.

There is a service class, WebserviceInvokerService,

class WebserviceInvokerService {
    @Override
    public void synchronized callBackFun() {...}
}

callBackFun ==> is the function which gets called when an event (some event) occurs.

In callBackFun I check DB and accordingly do a service call (no instance members of the class are involved in this business).

I have made callBackFun synchronized. There is a possibility that, multiple instances of WebserviceInvokerService will be created and callBackFun will be called on those objects.

I want callBackFun to be called "synchronously" across the objects. So will the "synchronized" for callBackFun will make any sense in such scenario.

Upvotes: 3

Views: 1048

Answers (3)

Paulo
Paulo

Reputation: 3008

To synchronize across instances, you should use synchronized with static reference.

class WebserviceInvokerService {
    @Override
    public void callBackFun() {
        synchronized(WebserviceInvokerService.class) {... } 
    }
}

Upvotes: 2

Lµk4s
Lµk4s

Reputation: 66

If you java multiple instances WebserviceInvokerServices the methods will be synchronized in each of these instances, but not across the instances.

What you might be looking for is a Lock.

You can try this:

private final static Lock lock = new ReentrantLock();

@Override
public void callBackFun() {
    lock.lock();
    try {
        // Do things here
    } finally {
        lock.unlock();
    }
}

EDIT: Added the final keyword as mentioned by @Wyzard

Upvotes: 2

Pavan
Pavan

Reputation: 858

Since callBackFun does not use instance members (as per post: no instance members of the class are involved in this business)

you can put this code in static synchronized method so that classlevel lock will be present. Call it from your instance method

public synchronized void callBackFun() {
    actualFunLogic();
}

private static synchronized void actualFunLogic()
{
   .....
}

Upvotes: -1

Related Questions