Executerservice submits task invokes code after time out - executorservice

I have below code, the doTransaction method is getting invoked after 20 seconds, could any one tell me why its taking that long to invoke doTransaction method.
Its not happening always its happening very rarely. Any help on this is appreciated.
Thanks,
ExecutorService service = Executors.newSingleThreadExecutor();
TransactionTask task = new TransactionTask(object);
Future<Result> future = service.submit(task);
Result r = future.get(20000, TimeUnit.MILLISECONDS);
class TransactionTask implements Callable<Result> {
private Request req = null;
public TransactionTask(Request trx){
this.req = trx;
}
#Override
public Result call() throws Exception {
Result o = doTransaction(req);
return o;
}
}

The above behavior could be explained if you submit multiple tasks.
The ExecutorService you created is single threaded, so it could only execute only one task concurrently. Other tasks if submitted will be in queue and will start executing if the former task is terminated/completed
It executes only after 20 seconds because in future.get(20000, TimeUnit.MILLISECONDS); you cancel the already running task. Could you check that you are not getting CancellationException.
Edit:
Since you are using Tomcat which is concurrent in execution, I would suggest, you use multithread instead of single thread if not necessary:- Executors.newFixedThreadPool(N); for having N tasks executing concurrently and increase the timout

Related

check asynchronous threads state in java

I have method in class MyClassB which is triggered asynchronously from a method of MyClassA:
public void getProductCall()
{
new Thread(new Runnable() {
#Override
public void run() {
try {
productRequest = service.createS4ProductRequest(getRepriceItems());
//Below is a rest call to another system
String response = pricing.getS4ProductResponse(quote.getAssetQuoteNrAndVrsn(), productRequest);
//I'm using the below 2 lines to check from ClassA's method to see if this process has ended
setProductResponse(response);
productPriceProcessEnded=true;
} catch (Exception e) {
productPriceErrorOccured=true;
e.printStackTrace();
}
}
}).start();
}
This is the piece of code in MyClassA i used to check if the above method is complete.
for(int i=0;i<1000000000;i++)
{
if(!networkAsynCalls.isListPriceErrorOccured())
{
if(networkAsynCalls.isListPriceprocessEnded())
{
return networkAsynCalls.getListReponse();
}
else
{
Thread.sleep(250);
continue;
}
}
else
return null;
}
instead of using this random for loop can i use some inbuilt method or service pool or something ?
Because,
1) This thread on method is in another class
2) In class MyClassB i have few more methods like this, so i need to check the status of all the methods in MyClassA
Thanks for any help.
If I undestand what you're trying to do is dispatch some code to be ran asynchronously, then be able to wait until it is completed (successfully or failed). If that's the case, you should take a look at Futures.
Here is an example based on the Javadoc:
FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {
public String call() {
// do stuff
return "result";
}});
This code creates an object "future" that can be invoked to execute searcher.search(target). At this point, the code is not executed at all. You simply have an object representing a computation that may be executed asynchronously. To do so, you'd call:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(future);
This snippet created an Executor (which is a fixed pool of 5 threads), then handed over the future to it for execution. The executor will run the computation from Future asynchronously.
Future offers some methods (see the Javadoc) to wait until completion, cancel, check completion status, etc. For example,
String result = future.get();
will block, waiting for the result indefinitely. A get(10, TimeUnit.SECONDS) will wait for 10 seconds and if the future has not completed, throw.

How to hit 1000 endpoints using multi threading in groovy?

I have a requirement to hit endpoints more than 1000 times to fetch some data from website. So i read some tutorials to use Multi Threading to achieving it. But at a time i want to use only 13 threads on same method.
So basically i am using ExecutorService to run 13 threads at one time:
ExecutorService threadPool = Executors.newFixedThreadPool(13);
for (int itLocation = 0; itLocation < locationList.size(); itLocation++) {
//some code like
ScraperService obj = new ScraperService(threadName,url)
threadPool.submit(obj);
}
threadPool.shutdown();
My Groovy Class named as ScraperService is implementing the Runnable interface.
#Override
void run() {
println("In run method...................")
try {
Thread.sleep(5000);
someMethod()
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Problem:
My problem is that my ExecutorService.submit(obj) and ExecutorService.execute(obj) is not calling my run() method of Runnable interface.
In Groovy/Grails:
There is also a executor plugin Executor Plugin in grails but i didn't found any appropriate example how to use it.
GPars is excellent for this type of thing.
Your ScraperService can just be responsible for handling the scraped data like below or maybe fetching it too, whatever.
import groovyx.gpars.GParsPool
def theEndpoint = 'http://www.bbc.co.uk'
def scraperService
GParsPool.withPool( 13 ) {
(1..1000).eachParallel {
scraperService.scrape theEndpoint.toURL().text
}
}
First of all i think there is problem in groovy service class with #Transnational annotation which doesn't allow to call run() method of Runnable interface. If you'll remove the #Transnational then it will call the run() method. It happened also in my case. But i am not sure, there may be some another reason. You can directly use:
ExecutorService threadPool = Executors.newFixedThreadPool(13)
threadPool.execute(new Runnable() {
#Override
void run() {
Thread.sleep(5000);
someMethod()
}
})
Extra (As i read your question)
If you are using multiple threads on same method then it can be complex as all threads will use the same local variables of that method which can occurs problems. It is better to use multiple threads for different different work.
But if you want to use same method for executing multiple threads then in my scenario it is better to use Executors.newSingleThreadExecutor().
ExecutorService threadPool = Executors.newSingleThreadExecutor();
newSingleThreadExecutor() calls a single thread so if you want to execute multiple tasks on it then it does not create multiple threads. Instead, it waits for one task to complete before starting the next task on the same thread.
Speed: newSingleThreadExecutor in comparison of multi threads will be slow but safer to use.
the threadPool.submit does not execute task
use threadPool.execute(obj) or threadPool.submit(obj).get()
instead of threadPool.submit(obj)
check the documentation for details:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)
example:
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
ExecutorService pool=Executors.newFixedThreadPool(3)
for(int i=0;i<7;i++){
int x=i;
Thread.sleep(444);
pool.execute{
println "start $x"
Thread.sleep(3000+x*100);
println "end $x"
}
}
println "done cycle"
pool.shutdown() //all tasks submitted
while (!pool.isTerminated()){} //waitfor termination
println 'Finished all threads'

ThreadPoolExecutor is not executing concurrently?

This is for my academic purpose only. Are the tasks that we add to the executor service are really executing in parallel. Well this is my example that raised this question
Runnable Class
public Tasks implement Runnable{
int taskCount;
public Tasks(int count){
this.taskCount = count;
}
public void run(){
System.out.println("In Task :"+taskcount +" run method");
}
}
Main Class
Class MyTest {
public static void main(String args[]){
ExecutorService service = Executors.newFixedThreadPool(10);
for(inti=0;i<10;i++){
Tasks taskObj = new Tasks(i);
service.submit(taskObj);
}
service.shutdown();
}
}
As soon as i submit a taskObj to the executor, the taskObj run() is invoked.
What if i have to something like this,
Add all the taskObj to the executor , the run() must not get invoked
Execute all the task objects at one shot. All the taskobj run() must be executed in parallel/concurrently
Please let me know
Thanks...V
If I understood you right, one way to solve this would be to use thread barriers. This might sound strange, but is actually implemented quite easy. You just take a variable (lets name it traffic-light) and make every thread loop on it. If you started enough threads (starting a new thread might consume some time) you just change it to green and all your threads will start execution at the same time.
For academic purposes we used to take an atomic-integer as counter (initialized with 0) and started n threads. The task of each threads was to increase the counter and then loop on it until it reached n. Like this you'll have all threads as parallel as possible.
If you still want to go with a thread pool system, you might have to implement your own thread system, where threads can wait upon a signal prior to grabbing work.
good luck

How to run a function after a specific time

I want to as if there is any way to execute a function after a specific time in windows phone 7.? For instance, see this code in android:
mRunnable=new Runnable()
{
#Override
public void run()
{
// some work done
}
now another function
public void otherfunction()
{
mHandler.postDelayed(mRunnable,15*1000);
}
Now the work done in upper code will be executed after 15 seconds of execution of otherfunction().
And I want to know is this possible in any way in windows phone 7 also.?
Thanx to all in advance..
Although you can use the Reactive Extensions if you want, there's really no need. You can do this with a Timer:
// at class scope
private System.Threading.Timer myTimer = null;
void SomeMethod()
{
// Creates a one-shot timer that will fire after 15 seconds.
// The last parameter (-1 milliseconds) means that the timer won't fire again.
// The Run method will be executed when the timer fires.
myTimer = new Timer(() =>
{
Run();
}, null, TimeSpan.FromSeconds(15), TimeSpan.FromMilliseconds(-1));
}
Note that the Run method is executed on a thread pool thread. If you need to modify the UI, you'll have to use the Dispatcher.
This method is preferred over creating a thread that does nothing but wait. A timer uses very few system resources. Only when the timer fires is a thread created. A sleeping thread, on the other hand, takes up considerably more system resources.
You can do that by using threads:
var thread = new Thread(() =>
{
Thread.Sleep(15 * 1000);
Run();
});
thread.Start();
This way, the Run method wil be executed 15 seconds later.
No need for creating threads. This can be done much more easier using Reactive Extensions (reference Microsoft.Phone.Reactive):
Observable.Timer(TimeSpan.FromSeconds(15)).Subscribe(_=>{
//code to be executed after two seconds
});
Beware that the code will not be executed on the UI thread so you may need to use the Dispatcher.

WCF InstanceContextMode.PerCall Services and Multi-Threading

I am running a self-hosted WCF Service (it will be a Windows Service but I'm runnning it as a Console App for debugging). The server side code needs to do some work when it is called. Then pass back the result synchronously to the client. It then needs to carry on and do some more intensive long-running processing.(ie asynchronously)
A simplified illustration of the code is :
[ServiceBehavior(IncludeExceptionDetailInFaults = true,InstanceContextMode = InstanceContextMode.PerCall)]
public class MyWCFService : IMyWCFService, IDisposable {
private Thread importThread;
private DoWork importWork;
public MyImportResultContract StartImport(MyImportRequestContract requestParams) {
processorResult = new MyImportResultContract();
//Simulate a short piece of work here to return results to the
//caller before calling a Thread to do more processing
processorResult.Success = true;
processorResult.Messages = "A message to pass back to caller"
Console.WriteLine("WCF Class ManagedThreadId = " + Thread.CurrentThread.ManagedThreadId);
//Thread off to do long running process
importWork = new DoWork();
importThread = new Thread(importWork.Start);
importThread.Start();
//Pass back the results
return processorResult;
}
public void Dispose() {
Console.WriteLine("WCF Class Dispose : " + DateTime.Now.ToLongTimeString());
}
}
internal class DoWork : IDisposable {
public void Start() {
Console.WriteLine("Thread ManagedThreadId = " + Thread.CurrentThread.ManagedThreadId);
//Simulate a long running process
Thread.Sleep(60000);
Console.WriteLine("Thread Finished");
}
public void Dispose() {
Console.WriteLine("DoWork Class Dispose : " + DateTime.Now.ToLongTimeString());
}
}
I have 2 questions:
1. I'm seeing the Dispose of the Service Class called before the Thread it spawns carries on and completes. My concern is that the Service class instance might not be getting released for Garbage collection because of the thread it spawns. Is the code outlined here solid so that this won't happen?
2. The service is self hosted in a Windows Service. What will happen if the service is stopped to any spawned threads ? Is there a way to get the service to wait until any Threads still running complete ?
Of course the service class can be disposed before the thread completes. If you wanted to wait for the work in the thread to complete, why start a thread? I'm not sure what behavior you expect/want other than this.
Yes, if the process is shut down your threads die. You have to implement a handler for the service stop callback which delays the shutdown process until all workers are complete. This will be easier to do if you use the more modern Task instead of Thread. Probably, you need to keep a global list of tasks in process so that your shutdown code can WaitAll on those tasks.

Resources