File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Doubt in Maxs' Socket solution 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 "Doubt in Maxs Watch "Doubt in Maxs New topic
Author

Doubt in Maxs' Socket solution

Arun Kumar
Ranch Hand

Joined: Aug 29, 2003
Posts: 67
I was going through the downloaded code of Dennys DVD. So i cannot quote which page of the book is the code i am talking about below. Sorry about that.
From what i understand from Maxs' solution using sockets, A ServerSocket runs continuously accepting connections from GUI clients (through accept() API), and spawns a Thread (if you have the codes - it is DBSocketRequest.java) just to serve that particular client. Once the run() method in that thread sends back the required info to that client, it closes the Socket object. But leaves the thread running. (Am i correct this far?). I dont see any place where the application registers the thread assigned to a particular client to reuse it. So if the same client comes back, a new thread will be spawned to server it. So at the end of the day multiple thread will be hanging, doing nothing. Will it nor cripple the machine running the "server" part?


SCJP (1.4), SCWCD, SCJD
Damian Ryan
Ranch Hand

Joined: May 09, 2003
Posts: 117
Arun, hi
taking a look over the code from Max's book I think I can answer your questions. (Before the man himself gives us the real answer ). The main server loop (in DVDSocketServer) listens on a ServerSocket and spawns a new Thread (a DBSocketRequest, actually, which is a subclass of Thread) to handle each client connection. This thread then handles the client/server I/O while the main server loop goes back to listening on the the ServerSocket in the main thread.
The DBSocketRequest gets the request from the client, performs the operation on the DVD database, sends the response back then the run method completes and so this Thread dies and its resources are released. And as the DBScoketRequest object was a local variable in the main server loop it isn't referenced anywhere else once the thread dies and so it goes out of scope and is eligible for garbage collection.
It is true that a new thread (DBSocketRequest) is spawned to handle each separate client request, which means that that the same client will be handled by different threads (newly spawned) even if it makes two consecutive requests, uninterrupted by other clients. This is a simple way to implement a stateless client-server protocol.
It is also true that spawning a new thread for each client request is processor and resource intensive, but I think what Max was probably aiming for in the book example was the elegance of simplicity. Yes, in a commercial server you'd probably use a thread pool, and perhaps keep threads alive to implement persistent connections between the server and particular clients, but these make the code more complicated and don't add to the fundamental points of socket communication that Max was probably trying to demonstrate.
Does this help at all?


Always proofread carefully to see if you any words out.
Arun Kumar
Ranch Hand

Joined: Aug 29, 2003
Posts: 67
Hi Ryan,
Sure your reply helped me.
I was thinking more on the line of why leave the Thread at the mercy of the garbage collector, to free the resource used by it. Because there is no way to ensure when the garbage collector will run and clean up the memory in VM.
Yeah like you explained we have other ways of implementing the same thing in a more elegant way.
Thankyou for your reply.
--Actually after reading your reply a second time i have few doubts about garbage collection. Because the main loop in the DVDSocketSever never ends unless you quit the server. So all the DBSocketRequest objects created (one for each request for a cleint) having local scope inside the main loop will never be out of scope, hence according to my understanding these objects will never be garbage collected. Is my idea of garbage collection incorrect?
[ September 18, 2003: Message edited by: Arun Kumar ]
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Hi Arun,
I was thinking more on the line of why leave the Thread at the mercy of the garbage collector, to free the resource used by it.
This is simply the nature of how things are done in Java. For example, when I declare

There is not explicit need to 'clear out' tmp. For that matter, even doing so won't actually 'clear it out'. It will still have to wait to the GC to run. Since Strings are Objects, this process makes a lot of sense.
I don't recommend spending a great deal of time and energy in making the program more elegant, unless by elegant you mean simpler. The graders will not appreciate extra complexity. My advice is to do the simplest thing that will fulfill the requirements. You are, of course, free to disregard that advice.
All best,
M


Java Regular Expressions
Arun Kumar
Ranch Hand

Joined: Aug 29, 2003
Posts: 67
Actually i was editing my reply to Ryan above, adding a question about garbage collection, before which Max posted his reply. Sorry for any confusion caused.
Can some one clarify my garbage collection question?
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Hi Arun,
I don't have a copy of the book here, but I'm guessing that the resources you're talking about are created inside the Run method, within the DBSocketRequest.run method. When that method finishes executing, those resources go out of scope. Very probably, the socket is closed towards the end of the DBSocketRequest.run method too.
M
[ September 18, 2003: Message edited by: Max Habibi ]
Arun Kumar
Ranch Hand

Joined: Aug 29, 2003
Posts: 67
I guess i need to make things clear about my question to even those who dont have the code with them or the book.
Server.java (assume this is the piece of code where the SeverSocket is created which listens for client sockets).
class Server {
public static void main(String[] args) {
//create the ServerSocket here
ServerSocket ssocket = new ServerSocket(3000);
while(true) {
Socket client = ssocket.accept();
//create a handler thread here which will handle the clients request
Handler hndl = new Handler(client);
}
}
}

class Handler extends Thread {
Socket client;
public Handler(Socket client) {
this.client = client;
}
public void run() {
//whatever the thread needs to do
//send info back to the client
client.close();
}
}
Yes the resources opened/used in the Handlers run method will be freedup at the end of the run() method.
But what will happen to the thread objects, which has a local reference in the Server.java's main() method, which will never end unless the server is shut down. So these THread objects will never be eligible for garbage collection (even if the System.gc is run). OR is it?
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Let's make the problem a little more generic: you may be able to answer it yourself.
In the following, does the tmp variable ever get garbage collected?


For that matter, what would happen in the following case?


M
[ September 18, 2003: Message edited by: Max Habibi ]
Arun Kumar
Ranch Hand

Joined: Aug 29, 2003
Posts: 67
Hi Max,
Ok, let me write down what i understand from my limited knowledge of garbage collection. Please correct me if i am wrong.
In the first case, the while loop never ends. And the Object tmp created will never be elligible for garbage collection. Unless there is a break; inside the while loop and the method holding this while block returns.
In the second case the Object created inside the while loop again will never be garbage collected, unless there is a break in the while loop. Here when the execution comes out of the while loop (may be beause of break , you are explicitly setting the Object reference to null, so the object is immediately elligble for garbage collection (need not wait untill the method holding the while block returns).
Arun
Philippe Maquet
Bartender

Joined: Jun 02, 2003
Posts: 1872
Hi Arun,
The first time "Object tmp = new Object();" is executed in the loop, a new Object is created. The second time, because of the assignment to the same reference variable, the previous created Object becomes eligible for GC, ... adn so on.
Max:
I don't recommend spending a great deal of time and energy in making the program more elegant, unless by elegant you mean simpler. The graders will not appreciate extra complexity. My advice is to do the simplest thing that will fulfill the requirements. You are, of course, free to disregard that advice.

I think that your implementation may be simple as far as it is consistent with your design choices, something like "I chose sockets over RMI for its simplicity".
In this thread, you'll see why I think (or thought) it's hard to defend. After Andrew's post, I changed my mind about that, even if I kept a little complexer - but more elegant IMO - solution.
Best,
Phil.
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Originally posted by Arun Kumar:
Hi Max,
Ok, let me write down what i understand from my limited knowledge of garbage collection. Please correct me if i am wrong.
In the first case, the while loop never ends. And the Object tmp created will never be elligible for garbage collection. Unless there is a break; inside the while loop and the method holding this while block returns.
In the second case the Object created inside the while loop again will never be garbage collected, unless there is a break in the while loop. Here when the execution comes out of the while loop (may be beause of break , you are explicitly setting the Object reference to null, so the object is immediately elligble for garbage collection (need not wait untill the method holding the while block returns).
Arun

Hi Arun,
In the first case, the object is eligible for garbage collection after each iteration of the loop. In the second, you get a compile error .
The reason I used the second example was to show how scope plays a role in all of this. Since the tmp variable(in the second case) is declared inside the while loop, it doesn't properly 'exist' outside of that loop. And since it doesn't exist, it would be eligible for garbage collection(if you didn't get a compile error, that is).
All best,
M
Arun Kumar
Ranch Hand

Joined: Aug 29, 2003
Posts: 67
Hi Max,
Thankyou,
The compile error in the second case is pretty obvious. Only after i saw your reply, i could see it though
Arun.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Doubt in Maxs' Socket solution
 
Similar Threads
Multi-Thread server, accept many clients but handles one at a time?
Doubt in Sockets!!
use of readLine versus read, reading from a socket, with C on the other end
Socket - Stream Corrupted Exception
Please find the problem in this code.