> Programming Languages > Java
Various Topics Home | Disclaimer | Report Adult Posts

Various Topics on Java



Java - "Java Server" in Programming Languages


Old 09-05-2004   #1
..onymo..
 
Default Java Server

Hi All,

Can anyone think of a better way to do this? I have a server thread that
waits for an incoming connection request. If the user wants to stop
'listening' then they call a method that sets active to false and calls
serverSocket.close(). This causes a SocketException which stops the run()
method from listening and then we just loop and sleep. The problem is that
looping and sleeping is wasted CPU time ... it'd be nice if I could just
sleep until the user wants to listen again - I don't want to keep creating
and destroying threads since that is resource intensive ... is there a good
way to do this?

public void run() {
while (true) {
try {
if (active)
connected(serverSocket.accept());
else
Thread.sleep(500);
} catch (InterruptedException e) { /* Continue */ }
catch (SocketException e) { /* Socket was closed */ }
catch (IOException e) { e.printStackTrace(); }
}
}


 
Old 09-05-2004   #2
..r.. ..p..
 
Default Re: Java Server

Anonymous wrote:

> The problem is
> that looping and sleeping is wasted CPU time ... it'd be nice if I could
> just sleep until the user wants to listen again - I don't want to keep
> creating and destroying threads since that is resource intensive ... is
> there a good way to do this?


Object.wait() and Object.notifyAll() are the tools for this job. Quite
possibly someone will post more detailed example code; if not (and it you need
it), then do ask more.

-- chris


 

Thread Tools
Display Modes





Powered by vBulletin®
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0