Reputation: 992
[JAVA] I am having a use case and I am wondering the best way to approach it. I have a current implementation in the following manner (pseudo-code), but it takes a lot of time to process:
Func (File) // Called when a file is uploaded
{
1.doSomething()
2.Result=LongRunningTask(File)
3.WriteToFS(Result)
}
Now I want to take out 2, & 3 and execute them in background and return quickly. If multiple calls are made to Func() , it should Queue and execute them one by one so the writing to FS is not affected. How should I go about it?
Upvotes: 1
Views: 2304
Reputation: 25
I'm not sure whether I have understood your question correctly. If your concern is how to execute 2 & 3 asynchronously, you can look into ExecutorService interface at http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html A good tutorial on executorService can be found at http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
Now, if you are looking at queuing up requests to the method, the easiest way is to synchronize it. It may not be a good solution from performance aspect but it is easier to implement.
Upvotes: 0
Reputation: 1146
You can use an ExecutorService to launch tasks in the background. The submit
method in ExecutorService
takes in a Callable<T>
and returns a Future
object immediately. You can use the Future
object to query the progress of the operation (whether its completed or canceled or still running) and to get the result of the operation after it's finished. You can manage how many concurrent background operations you allow by the size of the thread pool given to the ExecutorService
(a thread pool of 1 would allow you to queue background operations in called order, as you requested, but you could increase that number and allow concurrent operations).
Check out http://www.nurkiewicz.com/2013/02/javautilconcurrentfuture-basics.html for a good example on how to use ExecutorService
and Future
.
Upvotes: 2