Search code examples
javaenumeratethreadgroup

How does enumerate() method of ThreadGroup works?


The int enumerate(Thread[] list) function updates the specified list[] (of the calling function) with the info about active threads .How is it possible?? The list[] is passed as an argument to the enumerate function without it's reference and the function returns only an int value.So how does the changes made to list[] are reflected back in the calling function list[] ???


Solution

  • In Java everything is passed by value, but you're confusing a reference to the object instance with the object instance itself.

    In your case, the reference of array list[] is passed by value, this means that no matter if you modify the reference (for example doing list[] = new list[5], when the method ends, this new reference will be lost because it was passed by value (that is, a copy of the original value was sent to the method).

    But you can indeed modify the object instance pointed by this reference (for example list[5] = new Thread()) and when the method returns, this object will stay modified (if the object is mutable, that is).