Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Async and Synchronized

I have a Spring-based asynchronous method (annotated with @Async) that I want to pause in the case that an error event happened a certain number of times. Since there may be more than one thread doing the same kind of thing, I tried a static AtomicInteger (MY_COUNT) so that all threads can be aware of the count, and to make use of the built-in concurrency AtomicInteger provides.

In my unit tests (run with SpringJUnit4ClassRunner in Eclipse), all is well until the thread hits MY_COUNT.incrementAndGet(). Then the thread just disappears. No exception, nothing. The async worker thread just disappears. I tried taking out the AtomicInteger and just using synchronized methods, but the same thing happens.

Question: is there some kind of under-the-hood interaction between @Async and synchronization? Is it not possible to combine the two?


EDIT: more info: it appears that it has something to do with synchronization scope (if that's the right term). Once I removed the static designation from the counter variable, it still bombed; but then when I changed it to an Integer and moved the increment code to its own synchronized method, then the code proceeds. I haven't debugged the underlying Spring code; are there any Spring experts which might be able to shed light on this behavior?

like image 207
atrain Avatar asked Oct 28 '11 16:10

atrain


People also ask

Is Spring boot synchronous or asynchronous?

Spring Boot uses a SimpleAsyncTaskExector to run an async method. This Executor runs by default and it can be overridden at two levels- at the individual method levels or at the application level.

What does @async do Spring?

The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool. This class also customizes the Executor by defining a new bean. Here, the method is named taskExecutor , since this is the specific method name for which Spring searches.

Is Spring AOP asynchronous?

So the answer is: Yes, aspect advices like @Before or @After for Spring AOP will be executed asynchronously.

Can we use @async on private method?

Never use @Async on top of a private method. In runtime, it will not able to create a proxy and, therefore, not work.


1 Answers

No, async should not affect the behavior of the atomic integer.

With the given information, the only logical conclusion is that there is some exception that is not getting reported.

if it is possible for you, try setting the Uncaught exception handler

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.html

In the handler, ensure that you get the trace printed at the very least.

If this does not give you the solution, or you have a problem setting up an uncaught exception handler, post your code, so that we can help you.

like image 110
user1676688 Avatar answered Oct 12 '22 14:10

user1676688