How to implement Asynchronous Inter Thread Communication in java? - java

I am developing one code in which I have one parent thread and one child thread.Now, my scenario is like mentioned below,
Parent thread start the child thread
after starting the child thread it continuous to work what it is doing.
Now one time occurs that child thread want to call the method in the main thread
then it call asynchronously the main thread with that method.
I also want to clarify that I know the concurrency package in java but it is doing synchronously i.e. main thread have to wait for the child thread till it complete the execution,but I want the main thread to do continuous work while child thread executing.
My implementation is like SwingWorker Thread in java

You don't get to "call a method in the main thread". The only thing you can do is implement a specific mechanism whereby the main thread, by its own initiative, executes a method on an object which was provided by the child thread.
The above roughly describes what the Swing's mechanism does: the "main" thread (in that case, the Event Dispatch Thread) dequeues objects from a global queue and, if the object's type is appropriate, invokes the run method on an associated instance of Runnable.
Main point: in Swing the EDT doesn't "continue to work what it is doing"; it specifically waits for other threads to tell it what to do via this mechanism and otherwise just blocks, doing nothing at all.

Related

In JAVA can we make main method wait(sleep) for sometime when certain condition is meet in daemon thread?

In my main method i have started 1 daemon thread which runs in background to check certain condition is satisfied, if satisfied then my main thread should wait for sometime and then continue.
Is it possible to do so? Controlling Main thread from another thread.
Actually am trying to automate 1 application where there are many pop-up windows displayed and I want to use 1 thread in background to check for pop-ups, if pop-ups are displayed then my main method should wait for some time then begin again.
You can simply use the wait() and notify() on a common lock object.
From inside the main method, syncronize on the lock object. Within the synchronized block start your another thread and invoke wait() on the lock object.
In the run method of your second thread , write a synchronized block on the lock object and do your processing. Once it is done you can invoke the notify on the same lock object.
Main thread can then check if the required state has been set and then further actions can be decided (if you wish the main thread to complete its execution further or again wait and let second thread again do the processing) If you wish the second thread to again do (retry) the processing then like above you can invoke the notify() on the lock object and then can then invoke wait() on the same lock object.
This is the usual way of communication between two threads. But if its only single time process and you do not want it to happen multiple times then you can simply use the join() method. Main thread can join on the second thread. Till the second thread will be processing its task the main thread will be waiting for the processing to complete. Once the second thread is executed completely (end of run () method) control will reach the maim thread.
I suggest you to have a look at these methods. consumer-producer is a famous problem to understand these methods. You can also see these in action in an answer to another post.
https://stackoverflow.com/a/42049397/504133

Does each class have its own Thread by default?

I'm working with a GUI and I'm using
Thread.sleep();
in some of the classes, and I'm wondering if I need to create a separate Thread for my Main class (the GUI class), or if each class has a separate Thread by default. Note, the reason that I bring up Thread.sleep(); in the first place is that when working with GUI's Thread.sleep(); pretty much freezes your GUI. Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.
Thread.sleep() is a static method of Thread class. Hence, whichever class you place in a method, during runtime, if a thread call flow encounters this class method where Thread.sleep() in invoked, the thread will be blocked for that amount of time.
Your Question:
Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.
each class has a separate Thread by default -- INCORRECT Statement
-- Thread class is not inherited by every class
-- In normal sense, Thread is a call flow. It executes whichever class it encounters thru its method calls.
-- Class and Thread are 2 separate concepts.
---- Class is a definition of an entity,it cannot run by itself, it can be loaded, instantiated with data, method calls can be done and garbage collected.
---- Thread is an execution entity at run-time.It can be started, runnable, blocked, stopped. To support this concept, Java has provided Thread class or Runnable interface to extend/implement respectively.
do I need to create a separate Thread for my Main class?
-- your mainclass will be executed in a MainThread which is instantiated and started by your JVM.
-- It is better to define a seperate user-defined Thread to start your GUI.
-- If either in the MainThread (or) user-defined Thread, if it encounters Thread.sleep() during call flow, that particular thread will be blocked.
One more thing, your question is not clear on your need for usage of Thread.sleep(). You just have given a reason of the resultant usage of it but not the need for usage.
From javadoc for Thread:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to the
precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors.
Don't mind that the sleep() method is static, it is executed for the thread in which you call it. So if you call it from GUI, it puts your main UI thread into sleep, hence freezing UI completely.
by default the program does not have more than one thread. there should be only one class which has a main method. it does not matter it is a ui application or any other type of application.
please post the details in what scenario you want to use the sleep function.
When a java class is created automatically 3 thread are created by-default with it.
1.Main Thread
2.Thread Scheduler
3.Garbage Collector thread
Please watch this explanatory video to understand what a Thread actually is.
In this example the Thread is the music box, your code is the sheet of paper, and the processing time granted to a thread is the rotation of the handle.
So your main-class code (sheet-of-paper) is inserted into a thread (music-box) generated by the JVM and execution is started (handle rotates). Once you call sleep(1000) "rotations of the handle" is paused for 1 second, and so is the execution of your code. Thread.sleep() is just a short-cut to Thread.getCurrentThread().sleep().
If you now have several threads (music-boxes), you can of course pause one while another still runs. So if you have a main thread and a GUI thread, you can pause the main thread and your GUI will work fine (unless it actually tries to access the main thread). If you however pause the GUI thread, it will appear to be frozen.

Dispatch a task from EDT to main?

I've been reading a bit about concurrency (which gives me a headache).
I understand you can set a task to run on the EDT from the main thread using:
SwingUtilities.invokeLater
but can you set a task to run on the main thread from the EDT?
As in:
Thread mymainthread=Thread.currentThread();//<referring to the thread that initially kicks off public static void main
public void mousePressed(MouseEvent e){ //queue a task to run on mymainthread }
Can it be done? Is it a bad idea?
The other question on SO similiar to this (here) talks about creating a new thread but wouldn't it be safer and simpler to keep using the main if I was aiming for a single thread (+EDT) application? .......or maybe I've got this all wrong.
EDIT: What I should have explained: I wanted to create objects that would communicate with each other on the main thread (running in a slow loop) so I didn't want any of them be instantiated on a different thread, edt or otherwise.
but can you set a task to run on the main thread from the EDT?
I think you are confused on what EDT is. Swing and many other frameworks use a technique called thread-confinement.
In order to guarantee thread-safety, all actions are executed from a single thread. This thread in Swing is called Event Dispatcher Thread.
This thread has a queue and executes all tasks from that queue sequentially one at a time, at the same thread. This is why your tasks should be short in order not to block the UI.
So when you use EDT you are essentially passing a task to its queue from your thread and EDT will eventually execute it.
What you can do is put a task on the EDT queue which spawns a thread to be executed on separate thread. If you want to use your current thread for some reason as the background thread perhaps you could but why would you need that? The most straightforward way is just to submit a runnable to run as part of some background thread e.g. part of a pool
You can create your own event loop to do thread-confinement. This would allow you a separate single thread which would behave like the EDT. Be careful not to share [effectively] mutable objects between the two threads simultaneously.
Implementation can be as simple as a while loop with a BlockingQueue. You can go slightly higher level by getting an ExecutorService from java.util.concurrent.Executors.newFixeThreadPool(1).

Java - Run a runnable on an existing thread?

I am trying to switch back to an existing thread from a spawned child interface callback. Does anyone know how? The callback implementation always runs from the child thread where where it was called, not the implementing class...
What do you mean switch back?
Cause a context switch that will return you to "original" thread that spawned the child thread?
If so, this is not possible. It contradicts Multi-threading concepts.
If you want to have some work done on the "original" thread, while the "child" thread is running,
You can consider having a queue between the child and the original thread (i.e - Producer/Consumer).
The child thread will put a "job" on the queue, and the "original" thread will consume it.
However,the "original" thread will have to block on the the "child" thread.
Another way to implement this is using wait and notify, (child thread will notify) - but once again, original thread will have to wait.
Last approach will be to simply wait on the child thread execution to end, if you want to return to the original thread at the end of execution of child thread.
The question is - is waiting at the original thread is acceptable at your scenario?
You simply have the calling thread wait() on an object, and have the child thread notify() the same object.
When wait() is called, the calling thread will halt.
When notify() is called, the waiting thread will wake up and continue on.
These calls must be made within a synchronized block/method.
Swing uses the concept of an Event Dispatch Loop (EDL), and all Swing component interaction must run on the the EDL's thread. This sounds analogous to what you want to do, and to what zaske proposed in his response.
You might find the following helpful in formulating your solution:
SwingUtilities, in particulare it's invokeLater(Runnable) method.
SwingWorker if you want to get fancy and start even more threads.
Since this is also tagged java-ee I'll mention that you are not allowed to start threads in any Java EE app server. It introduces several issues:
Easy to bleed the server of thread resources
Can prevent undeployment of the application
Can prevent server shutdown if threads are not marked as daemons
Loss of functionality such as JNDI, Transactions, Security
It's generally a no-no. You might instead look into the #Asynchronous annotation which allows you to easily do fork/join kinds of logic safely with the cooperation of the container.
This answer has a very complete explanation of how #Asynchronous methods work including example code https://stackoverflow.com/a/6158773/190816

Java Thread to manage socket and run class method

I have a Java thread that I start so it keeps listening to a socket (considering the a socket read is blocking a thread is needed).
After the Thread receives the data from the socket it needs to call a method from a class.
Now I have two options to do this:
Declare an interface that is passed to the Thread and implemented in a class. When the thread calls the interface method the implementing classes will run it.
Or I can pass the class instance to the Thread as a parameter and then call the class method.
But I wanted to know if the thread blocks while the method is running.
I suppose so but I'm not sure.
I wanted the thread to have a Socket event behavior. What I mean is to only be responsible for reading the data from the socket and fire functions in the main Class, the one that called the Thread.
Yes, the thread will block while executing the method, so it can not read from the socket at the same time. No information will be lost, the transfer only takes longer and you can get a socket timeout if the computation takes too long.
If your method takes much time to run, you should execute it in another worker thread. I recommend to use an Executor for that.
You have various options :
Make your class a child class of Thread (easier code but you'll merge functionnal part - your main code - with a technical aspect (extending the Thread))
Make your class implements the Runnable interface and start a new thread with that Runnable (i often do like that). So your main code still remains in a overriden run method, but the inheritance tree is up to you (your main class can extend one of your other class)
Keep separated your main code / the thread with two classes (one for your main code, one for the thread), linking the two at your will (remember that if you make an inner thread inside another class, the inner thread can use any final properties, for example).
As stated in other answers, anything happening in your run() method is of course blocking the execution.
As a sidenote, if you're going to deal with threads and sockets, i strongly suggest you to have a look at NIO frameworks like Netty that are just there for this kind of behavior : event driven client/server application through NewIO sockets.
As another sidenote, i often use this pattern :
start an acquisition thread that will catch the event ;
push them in a linkedblockingqueue (queue.offer()) ;
have another thread that shares the same linkedblockingqueue (with queue.take()) : this operation is blocking, the threads will be blocked as long as the queue is empty ;
This is a very simple way to have one thread as "producer", and one thread as "consumer". You can even have various consumers awaiting on the same queue.
But I wanted to know if the thread blocks while the method is running
Yes it does block.
If inside run you call a method to process something it doesn't matter if that is an interface etc as you ask it only matters what does the method actually do
In your case you have only 1 option.
Make sure that you return the control back to your socket listening thread asap.
This can happen by designing/mandating the processing class to handle the processing in a different thread.
Actually your problem is not something new. In event based designs there is the requirement to process the event as fast as possible so as to not block the event queue based flow.
And this is how I would recommend you to design arround. Not use any interface to interact with the listening thread but register an event listener(s).
When an event occurs i.e. your listening thread reads data, it will pass the data as event to your listener(s) at which point of course it will block.
Then you should start a new thread to do the processing and the listening thread can continue with its work

Categories

Resources