0

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?

Bart
  • 19,692
  • 7
  • 68
  • 77
gunakkoc
  • 1,069
  • 11
  • 30

4 Answers4

1

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

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.

Miquel
  • 15,405
  • 8
  • 54
  • 87
1

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.

Vitaliy
  • 8,044
  • 7
  • 38
  • 66
0

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.

Community
  • 1
  • 1
mo.
  • 3,474
  • 1
  • 23
  • 20