Skip to main content

Developing a standalone server with HttpServer

3 replies [Last post]
byhisdeeds
Offline
Joined: 2006-01-06

I'mm trying to use HttpServer to develop a standalone HTTP server but when I execute the following code it starts the server but then ends.

What is the best practise way to start the server then wait forever while it processes requests. I've tried a Thread.sleep(very_large_number) but that can't be the best way?

HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 5);
httpServer.createContext("/", new TileServerRequestHandler());
httpServer.setExecutor(Executors.newCachedThreadPool());
httpServer.start();

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
forax
Offline
Joined: 2004-10-07

add these lines :
[code]
for( ; ; ) {
try {
new Object().wait();
} catch(InterrupedException e) {
// do nothing
}
}
[/code]
at the end of your code.
It's a forever loop.

Rémi Forax

mernst
Offline
Joined: 2005-02-19

> add these lines :
> [code]
> for( ; ; ) {
> try {
> new Object().wait();
> } catch(InterrupedException e) {
> // do nothing
> }
> }
> [/code]
> at the end of your code.
> It's a forever loop.

for very small values of "forever" :-) It'll throw an illegal monitor state exception.

I'd prefer
[code]
try {
new CountdownLatch(1).await();
} catch(InterruptedException ie) {
}
[/code]

forax
Offline
Joined: 2004-10-07

oups, i forget the synchronized :)
[code]
Object lock=new Object();
for( ; ; ) {
try {
synchronized(lock) {
lock.wait();
}
} catch(InterrupedException e) {
// do nothing
}
}
[/code]