简体   繁体   中英

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM