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
Related
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.
My android app has a long running background service, which I also understand runs in the application's main thread and for that reason, any time consuming or blocking task should be moved to a separate thread.
Now, here is the situation, I don't understand/confused about:
When I bind to the service from an activity, i receive an reference to the service which allows me to invoke service methods from my activity. One of the methods allows me to pass a String object from the activity to the service, which is then added to a BlockingQueue. A separate worker thread which is started in the Service's onCreate method, checks the queue for available data and then performs the required task.
What I want to understand is, if at some point, the queue becomes full and an attempt to the queue blocks, will it affect the main thread the service is running on?
Yes. In this situation, if the queue becomes full, the calling thread will block (in your situation, the main thread). So this is a bad design.
The produced data coming from a field of an Activity doesn't force you to use it on the main thread. I suggest you use some Handler for your producer running on its own thread which will allow you to make the processing (and eventually waiting on the queue) outside of the main thread.
This is also good for communicating with your Service since you can use Handlers to communicate with a Service (see Android Services' guide).
Finally, if applying the produced data can be passed directly to an Handler using either
Handler.post(Runnable) or Handler.send(Message)
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.
I'm writing a multithreading application, in my ServerThread.run() method, I use ServerSocket.accept() to receive new incoming connection. Everytime when a new connection arrives, ServerThread creates an other Thread named ClientHandler to handle the connection (Receiving/Sending data), and in my ServerThread, I have a java.util.HashMap<ClientHandler, Socket> to store the references of connected clients and the corresponding sockets.
In my ServerThread, I've implemented a few other public methods, such as shutdown() to stop the server thread, disconnect(int id) to shutdown the connection of a specific client etc. Those methods are usually called by my GUI, from the EDT thread.
I've tested the code, it works, but I'm not sure if it's the best way to do this. I've read lots of Java multithreading tutorials, but they don't add other public methods in their custom java.lang.Thread subclass.
Especially in my ServerThread.run(), I have used the method ServerSocket.accept() which is supposed to be blocking. When I want to shutdown my ServerThread, I have to call ServerSocket.close() to force the thread to stop.
However, when I call for example ServerThread.disconnect(int id) to close the connection of a remote client, it works. Is the ServerThread supposed to be blocking on the accept() method ?
So, my code works, but I don't know why, and I'd like to know if one can add other public methods in a custom subclass of java.lang.Thread ??
Thanks.
The reason you don't add public methods to a Thread class is exactly because this sort of confusion arises - there's an intuition that the Thread class itself 'owns' the execution of those methods, whereas in Java it is -always- the calling thread that owns the execution.
When the EDT thread calls ServerThread.disconnect(id), the code in the disconnect method is being run by the EDT thread, not the ServerThread. The key point here is that the Thread ServerThread, and the Object ServerThread are not quite the same thing, semantically speaking - an Object can't be "blocked" in the same way that a Thread can, the expression doesn't even make sense.
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