简体   繁体   English

异步调用同步方法?

[英]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. 由于我使用的是Spring框架,因此此任务非常简单,因此我仅使用@Async批注标记了该方法。

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 ). 但是,我的方法使用的是一个全局变量,该变量不能被多个线程同时使用(您可能会认为它是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. 为了确保该方法是线程安全的,首先要想到的是用synced关键字标记该方法。

But on the other hand it will be completely nonsense to use @Async annotation on synchronized method, right? 但是另一方面,在同步方法上使用@Async注释完全是胡说,对吧?

Is there any benefit to use @Async annotation on method that contains synchronized block ? 在包含同步块的方法上使用@Async注释有什么好处?

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,则应该查看Spring 5及其发布时提供的功能。

Spring 5.x 春季5.x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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