It's not a secret anymore!
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Will it ever be GCed? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Will it ever be GCed?" Watch "Will it ever be GCed?" New topic

Will it ever be GCed?

Zheng Huang
Ranch Hand

Joined: Dec 20, 2000
Posts: 49
Hi All,
The following is a server code. Can any one tell me when the newly created ServeOneJabber is available for GC? Please see line with comment "// When ServerOneJabber is available for GC?". Since it is created in the while(true) loop, it will never get GCed, Am I right?
// A server that uses multithreading
// to handle any number of clients.
class ServeOneJabber extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServeOneJabber(Socket s)
throws IOException {
socket = s;
in =
new BufferedReader(
new InputStreamReader(
// Enable auto-flush:
out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
// If any of the above calls throw an
// exception, the caller is responsible for
// closing the socket. Otherwise the thread
// will close it.
start(); // Calls run()
public void run() {
try {
while (true) {
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Echoing: " + str);
} catch(IOException e) {
System.err.println("IO Exception");
} finally {
try {
} catch(IOException e) {
System.err.println("Socket not closed");
public class MultiJabberServer {
static final int PORT = 8080;
public static void main(String[] args)
throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Server Started");
try {
while(true) {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
new ServeOneJabber(socket); // When ServerOneJabber is available for GC?
} catch(IOException e) {
// If it fails, close the socket,
// otherwise the thread will close it:
} finally {
} ///:~
Dave Boden
Ranch Hand

Joined: Nov 08, 2000
Posts: 37
OK. By GC you mean Garbage Collection.
If it were available for Garbage Collection at the point where you commented, the thread would not run.
The ServerOneJabber thread that you start will be available for collection when it stops and all other references to the thread have been destroyed (out of scope or set to null). A reference to the thread is kept by the Java runtime while it is running. Because you're not keeping any explicit reference of the threads you create, they will be available for Garbage Collection when the run() method finishes.
Hope this makes sense?
I agree. Here's the link:
subject: Will it ever be GCed?
jQuery in Action, 3rd edition