check asynchronous threads state in java - multithreading

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.

Related

Retrofit, call.enqueue

Here is my code:
retrofit2.Call<User> call = MainActivity.apiInterface.performUserLogin (username,password);
Log.d(TAG,"retrofit");
call.enqueue (new Callback<User> () {
#Override
public void onResponse( retrofit2.Call<User> call, Response<User> response )
{
Log.d (TAG,"in");
if(response.body ().getResponse ().equals ("ok"))
{
Log.d (TAG,"ok");
MainActivity.prefConfig.writeLoginStatus (true);
loginFormActivityLisener.performLogin (response.body ().getName ());
}
else if(response.body ().getResponse ().equals ("failed"))
{
MainActivity.prefConfig.displayToast ("Login Failed... Please try again...");
Log.d(TAG,"failed");
}
}
#Override
public void onFailure( retrofit2.Call<User> call, Throwable t ) {
}
});
I have question, why call.enqueue is not working? It is like it wasnt there. Its do nothing.
enqueue() function of Retrofit works asynchronously. It is a background task and runs the request on a background thread. If you debug your code, you will most probably see debugger skips the enqueue call and continues to execute next line. When background thread finishes, after skipping a few more lines maybe, it gets back to call.enqueue().
If you want to use a foreground task, you can choose execute() function, or there are other implementations to wait main thread until callback responses, like using events (see EventBus library).

What is the purpose of await() in CountDownLatch?

I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.
I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?
Class CountDownLatchSimple:
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
Thread one = new Thread(new Runner(latch),"one");
Thread two = new Thread(new Runner(latch), "two");
Thread three = new Thread(new Runner(latch), "three");
// Starting all the threads
one.start(); two.start(); three.start();
}
Class Runner implements Runnable:
CountDownLatch latch;
public Runner(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Waiting.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName()+" is Completed.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.
CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.
Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.
So in your example it would make sense to call await() at the end of main() method:
latch.await();
Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

CompletableFuture, supplyAsync() and thenApply()

Need to confirm something. The following code:
CompletableFuture
.supplyAsync(() -> {return doSomethingAndReturnA();})
.thenApply(a -> convertToB(a));
would be the same as:
CompletableFuture
.supplyAsync(() -> {
A a = doSomethingAndReturnA();
convertToB(a);
});
Right?
Furthermore, another two questions following as for "is there any reason why we would use thenApply?"
1) having big code for conversion?
or
2) need to reuse the lambda block in other places?
It is not the same thing. In the second example where thenApply is not used it is certain that the call to convertToB is executed in the same thread as the method doSomethingAndReturnA.
But, in the first example when the thenApply method is used other things can happen.
First of all, if the CompletableFuture that executes the doSomethingAndReturnA has completed, the invocation of the thenApply will happen in the caller thread. If the CompletableFutures hasn't been completed the Function passed to thenApply will be invoked in the same thread as doSomethingAndReturnA.
Confusing? Well this article might be helpful (thanks #SotiriosDelimanolis for the link).
I have provided a short example that illustrates how thenApply works.
public class CompletableTest {
public static void main(String... args) throws ExecutionException, InterruptedException {
final CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> doSomethingAndReturnA())
.thenApply(a -> convertToB(a));
future.get();
}
private static int convertToB(final String a) {
System.out.println("convertToB: " + Thread.currentThread().getName());
return Integer.parseInt(a);
}
private static String doSomethingAndReturnA() {
System.out.println("doSomethingAndReturnA: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}
}
And the output is:
doSomethingAndReturnA: ForkJoinPool.commonPool-worker-1
convertToB: ForkJoinPool.commonPool-worker-1
So, when the first operation is slow (i.e. the CompletableFuture is not yet completed) both calls occur in the same thread. But if the we were to remove the Thread.sleep-call from the doSomethingAndReturnA the output (may) be like this:
doSomethingAndReturnA: ForkJoinPool.commonPool-worker-1
convertToB: main
Note that convertToB call is in the main thread.
thenApply() is a callback function, which will be executed when supplyAsync() return a value.
In code snippet 2, the thread which invoked doSomethingAndReturnA() waits for the function to get executed and return the data.
But in some exceptional cases (like making Webservice call and waiting for response), the thread has to wait for long time to get the response, which badly consumes lot of system computation resources (just waiting for response).
To avoid that, CompletableFuture comes with callback feature, where once the doSomethingAndReturnA() is invoked, a separate thread will take care of executing doSomethingAndReturnA() and the main caller thread will continue to do other operations without waiting for the response to return.
Once the response of doSomethingAndReturnA is available, the call back method will be invoked (i.e., thenApply())

Windows service & mutilthreading

I have a windows service, which is executed regular intervals... Here is the code snippet:
protected override void OnStart(string[] args)
{
tickTack = new Timer(10000);
tickTack.Elapsed += new ElapsedEventHandler(tickTack_Elapsed);
tickTack.Start();
}
protected override void OnStop()
{
tickTack.Stop();
}
private void tickTack_Elapsed(object sender, ElapsedEventArgs e)
{
objProc = new Processing();
objProc.start();
}
In my start() method of Processing Class do my actual work like below.
public void start()
{
try
{
Process_Requests();
Process_Exports();
}
catch (Exception ex)
{
ErrorLogs.SaveError(ex, "");
}
}
How does the execution is happen when the execution done in a single thread??? For example, the first method takes time for execution then what about second method????
Now I want to call Process_request() and Preocess_export() methods. Each method should connect to multiple databases. In this situation, would I need to create new thread for each connection and do my work... I am not sure.
public void start()
{
try
{
#region
sqlConObjects = new List<SqlConnection>();
// Here i am getting multiple connection strings
List<string> conStrings = GetConnectionStrings();
foreach (string strCon in conStrings)
{
SqlConnection sqlCon = new SqlConnection(strCon);
sqlConObjects.Add(sqlCon);
}
foreach (SqlConnection sqlCon in sqlConObjects)
{
//sqlCon.Open();
Thread t = new Thread(ProcessRequest);
t.Start((object)sqlCon);
Thread t1=new Thread(ProcessExports);
t1.Start((object)sqlCon);
}
#endregion
}
catch (Exception ex)
{
ErrorLogs.SaveError(ex, "");
}
}
Can anyone please explain how to do this... is thread is created or no need??? How should the execution is happen if we are not creating a thread for each connection object.
Timer works on ThreadPool
From MSDN
The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads. The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the callback, or if all thread pool threads are in use and the callback is queued multiple times.
Also in your's code you don't keep reference to timer object and it will be collected.
As for me you should use ThreadPool. Createing a lot of threads is bad practice

c#: how terminate a background thread in dispose() method?

I have a program which runs a thread. The thread performs processing all the time and it uses some synchronized queue.
The class snapshot is as follows:
public class MyClass:IDisposable
{
private Thread myThread = new Thread(threadFunc);
private volatile bool runThread = true;
public MyClass()
{
myThread.Start();
}
public Dispose()
{
runThread = false;
}
private void threadFunc()
{
try
{
while(runThread){
queue.Take(); //This method blocks the thread if queue is empty. It uses Monitor class
//do some processing
}
}
catch(Exception e){...}
}
private void otherFunc()
{
queue.enqueue(...);//this method is executed by main thread and uses lock while adding element to the queue.
}
}
When I call Dispose() method, the thread exists threadFunc() method, but after a sec I get an execption from this func "Unable to avaluate expression...", as if the tread was terminated while doing some work. Maybe it has just released from queue.Take() blocking and has no context to run. I know I'm missing something...
How can I solve such problem and terminate the thread from the Dispose method.
Many thanks!!!
Use the overload of Take that accepts a CancellationToken. You can get a reference to a token by using the CancellationTokenSource which also has the Cancel method that you can call from Dispose to unblock the Take method. You can read more cancellation here.
Use the poison pill approach: See this thread

Resources