This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi all, In Java there are some methods, which return their result in the supplied parameter (most of the times array)... particulary the methods which return array of any specific kind of Objects. e.g. static int enumerate(Thread array) in Thread class.
Now my question is...why these methods' signatures are like this? Please, don't get me wrong, but why not the method is designed in such a way that it will directly return the array...and we dont have to supply it as a parameter?
there are number of such methods in io package also.
Is there any specific reason for this type of method signatures?
The method returns int...but fills up the passed array with the active Thread objects...my question is.... Why the method is designed in such a way...why doesnt it returns array directly...why do we need 2 pass it? [ January 24, 2005: Message edited by: Prasanna Kulkarni ]
I havent' used Thread.enumerate (or ThreadGroup.enumerate) in particular, but I've used other methods that work similarly, and - at least with the methods I know - the design choice was usually meant to *save allocations*.
In other words, if your method is called very often, and each time it needs to allocate a new array (and return it), then you're making it very hard on the Garbage Collector. On the other hand, if the method receives a pre-allocated array, then the programmer has a choice - he/she may use a single allocation.
One example I know is InputStream.read( byte ). Supposing to read a huge HTTP message, in blocks of 1024. Then you can use a single re-usable array:
From my experience, if you put a similar code on a loaded server, and let it allocate a new byte each time, the damage to performance will be quite noticable.
Perhaps another influence on this decision was the fact that another unrelated value needs to be returned. I'm too lazy to look at the API docs at the moment to find out what the int return value means here, but I'd bet that it wouldn't make sense to wrap it in a class with the Thread array. AFAIK, this would be the only other alternative to allow a programmer to return multiple values. This whole pass-by-reference to pseudo-return multiple values is a throw back to C which doesn't have classes at all.