Reputation: 1377
In my application, I am executing a bunch of SQL queries like a job and the details of the execution, which are inserted into a table. As soon as any record is inserted,the listener should pick it up and start monitoring the execution status and update the status in the same table.
My front-end is ready and till now I am able to execute the job(multiple queries) and insert the details in table. Now I want to capture the status of execution and also I should be able to end ,pause ,restart the execution.
While I am going through multithreading part, I came across ExecutorService.
My question is should I do this using ExecutorService? or is there any other way?
Please share any tutorial links.
Upvotes: 1
Views: 1142
Reputation: 38910
Yes. You can ExecuteService
, Callable
and Future
to achieve this.
Sample code:
import java.util.concurrent.*;
import java.util.*;
import java.util.Random;
public class CallableDemo{
public CallableDemo(){
System.out.println("creating service");
ExecutorService service = Executors.newFixedThreadPool(10);
System.out.println("Start");
List<MyCallable> futureList = new ArrayList<MyCallable>();
for ( int i=0; i<10; i++){
MyCallable myCallable = new MyCallable();
Future future = service.submit(myCallable);
try{
System.out.println("future.isDone = " + future.isDone());
/* You can use future.get() blocking call set time out*/
System.out.println("future: call ="+future.get());
}
catch (CancellationException ce) {
ce.printStackTrace();
} catch (ExecutionException ee) {
ee.printStackTrace();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
service.shutdown();
}
public static void main(String args[]){
CallableDemo demo = new CallableDemo();
}
class MyCallable implements Callable<Long>{
Long result = 0L;
public MyCallable(){
}
public Long call(){
// Add your business logic
// set the result
return result;
}
}
}
Key notes:
InterruptedException
, interrupt the current thread and proceed. shutdown()
Upvotes: 0
Reputation: 1437
Perhaps the answers to my question here could help a bit with capturing the status of a task.
how-to-get-to-futuretask-execution-state
While Executors framework is pretty powerful and could be used in almost any case, perhaps you should have a look at concurrency libraries like Quartz , which would have a lot of the problems you are gonna encounter if using Executors already solved.
Upvotes: 0
Reputation: 9574
I have used ExecutorService to run parallel unit tests. And found it very successful. So I would suggest that you use it. Refer to this
Upvotes: 0
Reputation: 7899
In your case i think you can use ExecutorService and create jobs in Callable objects that will help you to get the status of your running job it the form of Future objects.
For tutorial i would prefer this , it has basic information about concurrent package.
Upvotes: 1