Skip to content

Instantly share code, notes, and snippets.

@hibnico
Created April 11, 2014 17:04
Show Gist options
  • Save hibnico/10484586 to your computer and use it in GitHub Desktop.
Save hibnico/10484586 to your computer and use it in GitHub Desktop.
A bug in HttpURLConnection ?
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ConcurrentHashSet;
public class HttpURLConnectionBug {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
server.setHandler(new UniqueCheckHanlder());
server.start();
final AtomicInteger i = new AtomicInteger();
Runnable r = new Runnable() {
@Override
public void run() {
for (int n = 0; n < 1000; n++) {
String id = Long.toString(i.incrementAndGet());
int code;
String message;
try {
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/?id=" + id)
.openConnection();
connection.connect();
code = connection.getResponseCode();
message = connection.getResponseMessage();
} catch (Exception e) {
throw new RuntimeException(e);
}
if (code != 200) {
throw new RuntimeException("Unexpected code: " + code + " " + message);
}
}
}
};
for (int n = 0; n < 8; n++) {
new Thread(r).start();
}
}
private static class UniqueCheckHanlder extends AbstractHandler {
private ConcurrentHashSet<String> ids = new ConcurrentHashSet<>();
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String id = request.getParameter("id");
baseRequest.setHandled(true);
if (ids.add(id)) {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("OK");
} else {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().println("DUPLICATE");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment