Are the threads running out on shutdown?
I want to know if a stream is closed in java when the execution method ends.
I mean, I have a new stream declaration:
new Thread(new SubmitDataOnBackground(handler.getIDValue(), data, this.context)).start();
And then, in SubmitDataOnBackground, I have this launch method:
public void run() {
SubmitDataHandler submit = new SubmitDataHandler(ID, data, this.context);
submit.buildAndSubmitData();
}
After buildandSubmitData finishes, does the stream close or should I add some code somewhere?
I'm not sure if I'm leaving a new stream open every time I call this method, or if that's okay.
My application is a server, so it never ends because it is active all the time. I just want to know that the number of threads does not exceed the number, because it just creates new ones without closing the rest on completion.
source to share
Threads are closed after calling the run method. Read this for more info https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
EDIT: If you want to avoid this behavior, I recommend using ThreadPools.
source to share
Yes, the end ends when the method ends run()
. You can read more about streams and general compatibility here
One tip here - when using multiple threads that start and end all the time, it is recommended to use a thread pool. This is due to the fact that creating a stream is a rather cumbersome operation.
source to share
To actually stop the flow, the process is pretty simple. All you have to do is just run the method run
and return.
public void run(){
// implement your code
// Just about to return and the Thread will then stop soon after
}
Note that the thread will not necessarily be declared terminated immediately after the startup method completes, as the Java Virtual Machine (JVM) still needs to terminate its background, but it should terminate completely shortly after.
In other words, when a regular thread (also called a user thread) is created, it is expected to terminate and not completely shut down. The JVM will not terminate until all user threads have ended, or until a method call is made System.exit()
that will abruptly terminate the JVM .
EDIT: System.exit()
Doesn't stop the JVM suddenly, it does all shutdowns first. Runtime.getRuntime().halt()
stops the JVM without further processing.
source to share
Yes, threads are terminated after the specified jobs (sequence of instructions) in the method have finished run()
. However, the thread object that was created still exists, allowing it to be called again with Thread.start()
to create a new thread.
If you want to make sure that your thread start method ends before you continue doing anything else, try using the method Thread.join()
in the same place where you are working with threads.
Read this for more information: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29
source to share