Can you use Future/Futuretask objects with Spring TaskExecutors? - java

Is it possible to use Java FutureTask with a Spring TaskExecutor to get a Future object?
I'm looking for a TaskExecutor that implements the Java ExecutorService interface, in particular the submit() method. Looking through the Spring Javadocs doesn't reveal any classes like this. Is there some alternate method to handle futures through Spring TaskExecutors that I am unaware of?
If it is possible, could you also include an example?

Spring 3 has added submit methods with support for Future objects to AsyncTaskExecutor. Until then if you want access to Future objects I think you will need to get the underlying JDK executor (e.g. using getThreadPoolExecutor) and submit tasks directly on that.

Related

Do multiple calls to different methods in parallel in spring

I am fetching data from several different APIs. They are rest and soap web services. I have one id that I pass to each API one by one and get data in return. But each API takes few seconds to return the result and so the final response object that I create takes too much time.
My application is a Spring 4 Rest Service. What is the best way to call all these several APIs in parallel so that my Response time reduces to as less as possible.
Thanks.
You can use #Async annotation. You can find an example here
Daniel's answer is right but I would like to add something more to it. If you want to do something with your results but don't want to block with Future#get then I would suggest you to use CompletableFuture class.
It will let you add various actions which will be triggered on its completion.
There is also a really nice article on how to use CompletableFuture with Spring's #async annotation. Here it the link. Completable futures with Spring async

spring mvc: the difference between DeferredResult and ListenableFuture?

Spring MVC lets controllers return DeferredResult and ListenableFuture (which is implemented by ListenableFutureTask) to do async response. What's the difference? When should I use each of them?
They are conceptually similar to each other and can be used interchangeably as a controller's method result, thanks to ListenableFutureReturnValueHandler that adapts the second to the first one.
However, both DeferredResult class and ListenableFuture interface come from two different worlds:
First from org.springframework.web.context.request.async package added in version 3.2.
Second from org.springframework.util.concurrent package available since 4.0.
Moreover, they were added for different needs. While the first one provides a base and complete functionality for providing controller's result asynchronously, the second one allows you in addition to bridge your implementation with already existing classes/frameworks, like for example ExecutorService framework (see ListenableFutureTask).
So the bottom line is, use the DeferredResult class when it's enough for you to implement further processing on your own or ListenableFuture when you'd like to use ExecutorService-like frameworks.
DeferredResult is an alternative to Callable that allows you to produce a result. You can also extend DeferredResult to associate additional data or behavior, in case you need to access some data later without needing additional data structures. But that's about it.
ListenableFuture future comes in handy when you need to add callbacks to the asynchronous task. Guava's ListenableFuture actually allows for composition, which I don't see Spring's ListenableFuture to do.
For that you'd rather use CompletableFuture, which is also supported by Spring.
You can compose futures very simply, check this out: http://www.deadcoderising.com/java8-writing-asynchronous-code-with-completablefuture/

Strategies for exposing user identification from a REST endpoint back to the data-access/repository layer

The background: there is a requirement to attach auditing data to persisted entities, basically creation-timestamp + user ID and last-update-timestamp + user ID.
I'm not keen on passing the user ID as a method parameter through all layers/components. So I need to somehow pass user identifcation (derived from HTTP headers, the details are unimportant) through a REST endpoint (using RESTEasy, but that's probably not important, either) back to the data access/repository layer.
I've thought of using ThreadLocal but it feels a little hackish and might fail in a non-blocking IO environment. Maybe I'm wrong about that, not sure.
I also have a vague idea that AOP could help, though I'm not well-versed in AOP so not sure.
Any strategies appreciated, with or without code.
You can use entity lifecycle callback methods for your requirement: #PrePersist, #PostPersist, #PreUpdate, #PostUpdate.
It is one of the auditing strategies mentioned here.
It turns out that Spring's SecurityContextHolder is a reasonable place to do this (don't ask why the application isn't already integrating "properly" with Spring Security). It's basically the ThreadLocal option but with some nice interface around it.
The tradeoff is that you need to be acutely aware of the thread-bound nature of this solution. A controller that somehow uses other thread to do the work that needs the user context, will need to take some steps to make sure those threads can get it since they don't, by default, inherit the ThreadLocal. There is a mode you can set on SecurityContextHolder that will use inheritance of the ThreadLocal in any newly created threads, but that does not help if a thread pool is used (since threads won't be created by the request thread but rather pulled from the pool). Even then, most thread pools provide a way for the client thread to do "something" when obtaining and releasing threads, so it's possible to pass the security context on that way.

Quartz JobExecutionContext setResult vs put

I'm using Quartz Scheduler to generate an XML file and do something with the result. To do so I created a class implementing the Job interface, setup two JobListeners and tied them to my job. However I was needing to share data between the Job and the JobListeners.
Reading the API documentation I found there are two different ways of doing this:
Using the setResult and getResult methods of the JobExecutionContext.
Using the context's JobDataMap and thus the methods put and get.
Besides the fact that data in the JobDataMap is volatile, I see no difference of using either of the methods.
Is there any advantage of using one method or another?
I have verified your observations as correct. The only other comment I would make, after studying the source code here, is that setResult()/getResult() is both simpler to use and a simpler implementation, therefore the apparent superior choice for your purposes.

Executing code before and after #Transactional method

We have a Spring based application with a service layer which is annotated with #Transactional. We need to have code run before and after some transactional methods for the following reasons:
We need to synchronize access to the method based on a key. The thread needs to block before the start of the transaction.
We need to post a message on a queue if the transaction succeeds.
The options seem to be:
Create a class with similar methods to the service that can run the #Transactional method in a synchronized block and check for the return then post the message (would need a separate class due to AOP proxy problem). Services calling services, not nice, feels like a work-around.
Write an aspect to wrap around the #Transactional AOP which can do the synchronization and message posting. Might work but would rather avoid AOP.
Move the transaction down to the domain layer. Not desirable or possibly even feasible with the current implementation due to the way domain methods are reused in different workflows.
Code the transaction by hand in the service method and scrap #Transactional.
I would imagine this is a fairly common requirement. Probably I am missing an option 5, which is the obvious one!
I think I'd go with 2 unless you have some specific reasons to avoid AOP. Your problem is a classic example of where AOP can be used and it looks pretty good in the result. Here is a nice example of how to implement that (if you didn't read that already): Advising transactional operations
If AOP is really not an option, I'd go the 'Otherwise' option proposed by #Lawrence McAlpin.
Check out TransactionSynchronization callback interface. Spring can natively inform you what is happening with your transaction.
I would use a TransactionTemplate (your option 4) and programatically control the scope of the transaction in situations like this.
Otherwise, you could move the logic in your method out into a separate service, make that new service #Transactional, remove the #Transactional from the current method, and then surround the call to the new service with your pre- and post-transaction logic. I've taken this approach as well, but I prefer programmatic transaction management for requirements like this, as I think it's cleaner and, as you mentioned, services calling services (that are only ever needed by the first service) just feels like a hackish workaround.
if the key is being passed as part of the method call, then you can use java ReentrantLock to do the job.. its much simpler & cleaner.

Categories

Resources