I have made the simplest com.sun.net.httpserver.HttpServer below. What I don’t understand is why server.setExecutor(mainExecutorGood) works (when you to localhost:8080/test you get a response) but if you server.setExecutor(mainExecutorBad) doesn’t work (when you go to localhost:8080/test the browser hangs).
The full class is below.
package xxx;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class ServerTest {
@SuppressWarnings("restriction")
public static HttpHandler testHandler() {
return new HttpHandler() {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
// TODO Auto-generated method stub
try {
String rt = "Test OK";
byte response[] = rt.getBytes("UTF-8");
httpExchange.getResponseHeaders().add("Content-Type", "text/plain; charset=UTF-8");
httpExchange.sendResponseHeaders(200, response.length);
OutputStream out = httpExchange.getResponseBody();
out.write(response);
out.close();
} catch (IOException ucx) {
LogManager.getLogger().catching(ucx);
throw new RuntimeException(ucx);
}
}
};
}
@SuppressWarnings("restriction")
public static void main(String args[]) {
int port = 8080;
try {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
ThreadFactory tf = new ThreadFactory() {
final AtomicInteger id = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread();
int tid = id.getAndIncrement();
t.setName("http_server_worker_thread_" + tid);
return t;
}
};
Executor mainExecutorBad = Executors.newCachedThreadPool(tf);
Executor mainExecutorGood = Executors.newCachedThreadPool();
server.setExecutor(mainExecutorGood);
server.createContext("/test", testHandler());
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread.currentThread().setName("main_thread");
server.start();
} catch (Throwable tr) {
System.err.println("throwable problem");
}
}
}