简体   繁体   中英

Asynchronously calling synchronized methods?

I want to benefit from asynchronously calling one of my methods. Since I use spring framework, this task is quite trivial, so I just marked the method with @Async annotation.

However my method is using a global variable that is not intended to be used concurrently by multiple threads( you may think of it as javax.jms.Session ). First thing that comes to mind to mark the method with synchronized keyword in order to make sure that method is thread safe.

But on the other hand it will be completely nonsense to use @Async annotation on synchronized method, right?

Is there any benefit to use @Async annotation on method that contains synchronized block ?

The purpose of making something asynchronous is that it will do things in the future, that will take relatively much time, for example file or database operation, and during that time, you can make other useful operations .

In your case, if you do synchronous block inside and async operation, you will lose async functionality making that part of your code block in certain cases. Of course, if you access a shared resource concurrently, you should defend it, the real question here, is that you really need async functionality inside that function? Maybe you can refactor your code to deal with the synchronous resource somewhere else.

Also if you are really into async functionality, and spring, you should check out Spring 5, and what it has to offer, when it's released.

Spring 5.x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM