Gokul Kulkarni Gokul Kulkarni - 1 month ago 14
Java Question

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.

Answer

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 static Lock lock = new ReentrantLock();

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