Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

quick question

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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."
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
sunglasses are a type of coolness prosthetic. Check out the sunglasses on this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic