Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
Gokul Kulkarni Avatar asked Jul 02 '26 19:07

Gokul Kulkarni


1 Answers

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

like image 65
Lµk4s Avatar answered Jul 05 '26 12:07

Lµk4s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!