Will the PrintWriter object will be garbage collected if we use flush() but not close() method in java?

164 views Asked by At

In the following code, i'm sending message (broadcastMsg) to all list of socket connection specified in the clientSocketLister.

The PrintWriter object is initalized with autoFlush enabled !

My question is - Will the PrintWriter created in the for loop will be garbage collected even if there is no close() method to close the stream ?

Please, help !!

for(int i = 0; i < size; i++)
{
    Socket clientSocket = (Socket)clientSocketLister.get(i);
    //PrintWriter with autoFlush enabled
    PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true); 
    writer.println(broadcastMsg);
}
1

There are 1 answers

0
user207421 On BEST ANSWER

The PrintWriter object becomes eligible for GC when there are no more reachable references to it. Whether it has or hasn't called close() has nothing to do with it whatsoever.