Java - Run a runnable on an existing thread? - java

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

Related

Java - State pattern: Using threads within the states

I want to coordinate serial requests coming from a Java Swing GUI using the state pattern. When a state method was called, the serial communication shall start and in parrallel the GUI should not be frozen during this time.
I have one GUI Thread. In this thread I'm invkoing methods of a state machine which also lives in the GUI Thread.
In some cases after a state machine method has been invoked, data from a serial port shall be fetched (longer task). This fetching is been done in an otherThread. On some state changes the otherThread can be interrupted and otherThread should stop immediately (I'm using otherThread.interrupt()). To know when otherThread actually has returned, I use otherThread.join() to wait for otherThread in the GUI Thread.
Without using join() I always run into exceptions after a state change where I communicate via serial port in another otherThread.
The inconvinience of this approach is ofc. that the GUI thread is blocked/frozen as long as otherThread needs to finish its task.
I was thinking about calling the state machine method in a third thread. But I don't like this idea bcs.:
I don't have a lot experience with multi threading in Java (I assume labeling the methods of the state machine as synchronized could work to ensure thread safetiness).
Overhead due to thread and runnable creation for each invocation of a state machine method.
So my question is: What is a good way to make the GUI not frozen while waiting for otherThread?
All the stuff about "states", "state machines", and "state pattern" is red herring. (Meaning: it is completely irrelevant.) The question is simply how to avoid block-waiting for Thread.join() from the gui thread.
Your "otherThread" should be aware of the fact that it was interrupted and exit gracefully. (Look for more information on thread interruption in Java to see how to accomplish this correctly.)
Right before exiting, the "otherThread" should post a message back to your "gui thread" to let it know that it is exiting.
Posting a message back to the "gui thread" in Swing is done with SwingUtilities.invokeLater(), and the "message" is not exactly a message, it is a function that you pass to invokeLater() and it gets executed within the "gui thread".
Then, the "gui thread" can then either ignore the thread, or join with it, knowing that this Thread.join() will complete very quickly because thread termination is either imminent, or has already happened.

Is there standard implementation for thread block/resume in java SE?

I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple.
Is there any ready to use solution? Preferably in java SE 6? Or do I have to use my own implementation? I couldn't find any.
Update
More specifically. I need work->block->external release->work->end behavior from thread 1 and ability to release block from thread 2.
have a a look at the classes in java.util.conucurrent ...
CountDownLatch might be a solution for your problem if i understand your problem correctly.
I need to block execution of a thread until resumed from another thread.
Not enough information. Do you need an on/off switch that is controlled entirely by one thread and obeyed by the other? That might be a good application for a Turnstile: Pause thread from another thread(s) and also stop/start it yet from another thread
Or do you need "one-shot" behavior? (i.e., the "background" thread does one thing each time the "foreground" thread gives it permission to go.) That would be a good application for a java.util.concurrent.Semaphore.
Or, do you need some other behavior?
using an ExecutorService and calling invokeAll might also be an option.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
this way lets you also specify a timeout in which all tasks should have been finished. Which is generally a very good idea, if you want to have a responsive application.
Inspired by other answers, I found two solutions:
First:
Create Semaphore with no (0) permits:Semaphore semaphore = new Semaphore(0); in first thread. And share reference to it with your second thread.
Do some work in the first thread and call semaphore.acquire(); when you wish to stop execution.
Some time later call semaphore.release(); from second thread to unblock the first one.
Second:
Create CountDownLatch with initial count 1: CountDownLatch countDownLatch = new CountDownLatch (1); And again, share reference to it with both threads.
Call countDownLatch.await(); when you wish to block execution of the first thread.
The first thread can be resumed by calling countDownLatch.countDown(); somewhere in the second thread.

How to implement Asynchronous Inter Thread Communication in 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.

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

Stopping and Restarting a Thread

I am trying to stop a current thread, change the run() method, and then restart that thread. I've looked around, and most of the methods are deprecated. However, interrupt() is not. I'm not sure if that's all you need to do.
interrupt();
start();
Would that work for what I needed it to do? It says that you should never start a thread more than once, and I don't know if it means
start();
start();
Rather than what I wanted to do.
Any help is appreciated.
Thanks
No, you can't do that. Fron the java online docs:
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Don't restart a thread. You ALWAYS can rewrite your buisness logic to do this some other way. Consider using SingleThreadExecutor
In this case, you should create a Runnable object and pass it to a thread. Then you're creating different threads, but re-using the 'work' object.
Once you've started a thread, you can only interrupt it. Once you've done that, you can't start it again. See here for more details.
I'm not quite sure what you want to do, but it sounds like you have different Runnables that you want to run in sequence. In this case use a SingleThreadExecutor and submit your Runnables. It will run these in order, and so interrupting the first (successfully) will invoke the second.
I'm still not sure this is a good idea (it just doesn't sound right) and perhaps posting a more detailed problem description will give people a better idea of what you're really trying to do.
You should look into the basics of threading more. A thread can only run once. If you want to have the thread run different code, you need to create a new thread.
The interrupt() method will not stop a thread immediately (there is no supported) way to do that, it will stop only at certain points by throwing an InterruptedException().
I think you're approaching your problem in the wrong way. You cannot 'change the run() method of a Thread'. However what you probably want is to stop the previous thread and create a new one with a different run() method.
One thing to keep in mind however, is that Threads are designed to be as autonomous as possible and they don't like interference from other threads, which is why suspend() and resume() are deprecated. They create all sorts of bad behaviour depending on the circumstances and also prone to deadlocks.
You have 2 perfectly safe alternatives however:
Use wait() and notify() on a specific shared object.
Use sleep() and interrupt()
You need to decide within the run() method where it is safe to 'stop' the thread, and at that point put a wait() or sleep(). Your thread will only stop at that point.
The other thread can then do a notify() or sleep() so that the running thread is notified or interrupted. In case of interrupt() you will get an InterruptedException which you can use to terminate what you were doing in that thread.
After interrupting the old thread you can start a new thread initialised with a new Runnable implementation which has the different run() method.
Calling interrupt() will set the thread's interrupt status potentially interrupting blocking methods. This is part of a cooperative cancellation mechanism. You can't use it to force the thread to stop running.
Stopping threads has been deprecated for a reason: it is inherently dangerous as it may leave the state variables which it is manipulating in an inconsistent state.
You should not do this. Make your code from the run() method into a Runnable and submit it for execution to an Executor. This will return you a Future which you can use to retrieve its results as well as to cancel it.
If you want to reuse the same thread for other computations, use a thread pool, see for example Executors.newFixedThreadPool() and other factory methods in Executors.

Categories

Resources