Java what does a thread do when it's done running? - java

In a game I'm making I use many instances of a thread, and it does not keep track of them.
clientThread cT = new clientThread(socket);
new Thread(cT).start();
What I need to know is that when an instance of the tread has finished(all the loops have been completed and it is no longer being used), just like an instance of a method, is it discarded? Or do I need to use a special piece of code to discard it?

The thread is a normal object, which will be garbage collected like any other object. In the case of a thread object, it becomes eligible for collection when the thread exits.

It will be discarded as soon as run() completed. You don't need to add any special piece of code to release .
Note: Discarded doesn't mean, it's gone from memory (but it won't run further). It may be GCed when next GC collection runs.

If the garbage collector gets to it it will be destroyed.

The other friends answered exactly what you ask. One comment only.
I'm making I use many instances of a thread, and it does not keep
track of them.
Do NOT do this: new Thread(cT).start(); I.e. start spawning threads.
Read about thread pools and ExecutorService

Related

At which point in the lifecycle is the "stack" of a Java Thread created and destroyed?

I am considering extending java.util.Timer, and completely overriding all public methods, to use a different implementation. The one "problem" I see is, that Timer instantiate and starts a Thread in it's constructor, which I cannot use, due to it being "private". So I would like to not waste the "resources" used up by that Thread. I see at least one things I could do, which is to call super.cancel() directly in the sub-class constructor, thereby immediately closing the thread.
My question is: When are the "resources" of a java.lang.Thread allocated and released?
Allocation: At instance instantiation, or at call of start()?
Release: At "end of run()" or at instance GC time?
If it's JVM implementation specific, I'd like to know how the Oracle JVM does it?
Generally, when you instantiate an object you allocate space in memory for it. This is the case when you create a Thread object as well. It is making perfect sense, as you might wonder how can you use an object which is not stored in the memory. A Thread object does not use a lot of memory though. On the other hand, when you call the start() method the run() method of the Runnable is called and all the resources associated to the Thread will be allocated there. If the Thread is no longer running, then all the otherwise unreferenced resources used by the Thread will be de-allocated by the garbage collector eventually. So, if you ask me I think your approach to stop the Thread is good, this way only the Thread object will remain in the memory along with any other resources you reference.

Is it necessary to store a cachedthreadpool?

In my app I need to execute different future task.
My call would be something like
public Item getTaskResult(){
//creating the task object named task
Executors.newCachedThreadPool().execute(task);
....
}
Is it wrong to just call Executors.newCachedThreadPool() ?
Should I keep a reference to it? Am I wasting some resources doing in my way?
You should probably have only one CachedThreadPool in your whole application. Doing so, it allows you to factorize resources associated to the pool and also to take advantage of a better thread re-use.
Creating a thread pool every time is a costly operation. Therefore create it once and use it as much as you want.
Take it this way: In your house, would you want to create a new swimming pool every time you need to swim? Create just one CachedThreadPool and use it.
The worst problem with your demonstrated code is that it has a resource leak. The thread pool will not be automatically closed, and threads killed, just because it has become unreachable. You may observe your thread count growing without bounds, until finally you get an OutOfMemoryException: cannot create a native thread.
You can legally submit a task to a new thread pool and immediately call shutdown on it. This will work correctly, even if failing to be the most performant option.
On a different level of approaching this issue, thread pools are not designed to be used in such an ephemeral fashion. You are degrading the pool to what a raw Thread instance would do, where the main point of using a thread pool is... well, pooling threads, which are expensive system resources. This is why a global singleton is the preferred approach to using the Executor Service.

start a new thread in catch

I have a class (class A for example) implements Runnable. In run method I have a try catch.I want to start a new thread in catch like this
new Thread(new A()).start();
Is this a true manner to handle exceptions?
I mean maybe its a dangerous way because the heap will get full very soon; in other words garbage collector will not garbage this object because another object has been just created in it.
I mean maybe its a dangerous way because the heap will get full very soon; in other words garbage collector will not garbage this object because another object has been just created in it.
It is not dangerous for that reason. If we assume that new Thread(new A()).start(); is the last thing that the original thread does before it exits, then by the time we need to GC the original thread will have exited, and hence its stack contents won't be reachable. The only thread that will still be reachable will be the one that it still alive.
However, it is dangerous if the new thread is liable to repeat the computation and then throw the same exception again, and again, and again ... So if you do write code like this, it is a good idea for the application to keep a track of how often the thread is being re-launched, and pull the plug if it happens too often.
The other problem with the code as written is that the code that launched the original thread sees it die, but doesn't hear about the new thread. That is problematic if your want to initiate shutdown by interrupting the worker threads.
If you put those two problems (and others) together, it is better for the code that launched the original thread to be responsible for relaunching.
Thread is new parallel light weight process. As soon as its run method completed it will be eligible for GC. I don't think it effects GC life cycle of the object from where it started.
Only one new thing in your case is, handling exceptions with thread. Without knowing more details about why you want this, its hard to tell is it safe/good practice.
This is not a very good way of handling exceptions within a thread. Why would the newly created thread of the same type not have the same exception?
What you should do is have some form of thread manager up a level from the thread that will monitor for, handle, and if necessary recreate new threads when old ones fail.
This will allow you to add more ways to handle the error, and will look a lot neater if you try and debug the threads. instead of having all these hanging threads (cause the parent was cleaned by GC) you'll know all threads have spawned from the same location.
What you are proposing will not clutter the heap because threads will be GC'd when they have finished running.
If you didn't store any references to the thread that you'd created - it will be cleaned by GC when terminated. In your case I think it's pretty safe to start a new thread inside run() method.
Just be sure you are not creating inner classes or storing this thread instance - it can cause memory leak, of course.
Good luck

Does removing an item from a list of class extending runnable terminates its thread?

I'm writing a chat server in Java. I was using a fixed array of runnable classes where each element in array represents a client. The threads created are in an infinite loop which reads from socket stream.
Now I want to do it with a list so I don't have to worry about array size and it sounds more legit way of doing it. However I couldn't be sure if removing an item also terminates the thread. Actually I have no idea what it does. Also, I'm wondering is there any other possible issues with using list in that kind of situaton. Finally, how about array of Timer? Since I've used Timer for each client, again, does removing a Timer from a Timer list also stops its schedule? Any possible problems?
An object exists in itself - storing a reference to that object in a list does not change its behaviour.
So if you have a Runnable task which is running in a thread, adding it to / removing it from a list does not make a difference to that Runnable and the thread will continue running it.
The same applies to a Timer and any other objects.
Side note: there is one situation where removing an object from a list can make a difference: it is if that object is only reachable through that list. After being removed, because it is not reachable any longer, it becomes eligible for garbage collection. But that does not apply to a running thread or active timer.
You have a thread object. A reference to it was inserted into an array. Adding or removing the reference from the array (i.e. the thread) is not going to cause any unknown side effects, so you are good. If you want to stop the thread you will have to implement that either internally in your run method. Garbage collection is not an issue here.
Timer's the same issue again: they are all object references.
A running thread is considered a so called garbage collection root. Anything that is a root or can be (indirectly) referenced from the root will not be garbage collected. When the garbage collector determines whether your object is 'reachable' or not, it is always doing so using the set of garbage collector roots as reference points.
Hey there i will refer to this question!
If the thread is started it will not garbage collected as it is referenced by the containing thread.
It will garbage collected if it is done or not started yet!
The reason for this is, when started the thread-object gets added to the current ThreadGroup (a bit more complex under the hood :) ) and when its done it will automatically removed.

Java starting a thread pool in objects constructor

Is it safe to start a thread pool in an objects constructor? I know that you shouldn't start a thread from a constructor, something about the "this" pointer escaping (I don't exactly understand this, but will do some more searches to try and figure it out).
The code would look something like this:
private ExecutorService pool;
public handler()
{
pool = Executors.newCachedThreadPool();
}
public void queueInstructionSet(InstructionSet set)
{
pool.submit(new Runnable that handles this instruction set);
}
If that doesn't work, i could just create this class as a Runnable and start it in a new thread. However, that seems like it would be adding an unnecessary thread to the program where it doesn't really need one.
Thanks.
EDIT:
Thanks for the replies everyone, they definitely helped make sense of this.
As per the code, in my mind it makes sense that this constructor creates the thread pool, but let me explain what specifically this code is doing, because i may be thinking about this in a weird way.
The entire point of this object is to take "Instruction Sets" objects, and act on them accordingly. The instruction sets come from clients connected to a server. Once a full instruction set is received from a client, that instruction set is sent to this object (handler) for processing.
This handler object contains a reference to every object that an instruction set can act upon. It will submit the instruction set to a thread pool, which will find which object this instruction set wants to interact with, and then handle the instruction set on that object.
I could handle the instruction set object in the IO server, but my thoughts are having a separate class for it makes the entire code more readable, as each class is focusing on doing only one specific thing.
Thoughts? Advice?
Thanks
Your sample code doesn't let "this" escape at all. It's reasonably safe to start a new thread in a constructor (and even use this as the Runnable, which you don't in this example) so long as you're sure that you've already initialized the object as far as the new thread will need it. For example, setting a final field which the new thread will rely on after starting the thread would be a really bad idea :)
Basically letting the "this" reference escape is generally nasty, but not universally so. There are situations in which it's safe. Just be careful.
Having said that, making a constructor start a thread might be seen as doing too much within the constructor. It's hard to say whether it's appropriate in this case or not - we don't know enough about what your code is doing.
EDIT: Yup, having read the extra information, I think this is okay. You should probably have a method to shut down the thread pool as well.
I agree with Jon.
Furthermore, let me point that you're not actually starting any actions on the thread pool in the constructor. You're instantiating the thread pool, but it has no tasks to run at that point. Therefore, as written, you're not going to have something start operating on this instance before it finishes construction.
It sounds like the thread pool would be owned and used by the object; threads wouldn't be pass out of the object. If that's the case, it shouldn't be an issue.
Constructors create an object and initialize its state. I can't imagine a use case where long-running processes are required to do so.
I can see where an object might interact with a thread pool to accomplish a task, but I don't see the need for that object to own the thread pool.
More details might help.
I think it's OK to start a thread pool in the constructor of the object as long as that object fully manages the lifetime of that thread pool.
If you go this path, you will have to work extra hard to provide the following guarantees:
If you constructor throws any exception ( both Runtime and checked ), you must have cleanup code in the constructor that shuts down the thread pool. If you don't do this and create a thread pool with non-daemon threads then, for example, a little console program that uses your object may stay up forever, leaking valuable system resources.
You need to provide something that I call destructor method, similar to close in Java I/O. I usually call it releaseResources. Notice that finalize is not a substitute for this method, because it is called by GC, and for an object with reasonably small memory footprint it may never be called.
When using this object follow this pattern
->
MyThreadPoolContainer container =
new MyThreadPoolContainer( ... args to initialize the object... );
try
{
methodThatUsesContainer( container );
}
finally
{
container.releaseResources( );
}
Document that object constructor allocates limited resources and the destructor method has to be called explicitly to prevent their leakage.

Categories

Resources