• Post Reply Bookmark Topic Watch Topic
  • New Topic

quick question  RSS feed

 
jambeard lewistrix
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The below code is supposed to work like this; if a client connects, start a new thread, repeat forever (ie, do this everytime a client connects).



Does this do what I think it's supposed to do? At the moment I can't test it properly, all I need to know is: when a client connects and the server starts a new thread will this then continue to wait for connections from other clients (and start new threads when they do connect) or will it wait until the thread has stopped running then wait for another client to connect?

J
 
Paul Santa Maria
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes:
1. "accept()" will block until a new connection arrives

2. You then create a new thread object and invoke its "start()" method

3. The original (server) thread will immediately return back to the
main loop to wait for the next connection.

4. A thread will not wait on another thread unless you call that
thread's "join()" method. Which, in this case, you're not doing,
and you don't *want* to do.

So the answer to your question is "Yes, your code will be truly concurrent."
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's the basic structure for almost every server. If you'll have lots of connections over time the overhead of creating new threads for each client connection can add up. In JDK 5 look into thread pooling, start with Executor in the JavaDoc. Here's one of mine:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!