Skip to content

Instantly share code, notes, and snippets.

@murayama333
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save murayama333/418b0eabfa4640644611 to your computer and use it in GitHub Desktop.
Save murayama333/418b0eabfa4640644611 to your computer and use it in GitHub Desktop.
package com.example.app;
import java.util.Random;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Response;
@Path("/async_cc")
public class CompletionHandlerAsyncResource {
private static int numberOfSuccessResponse = 0;
private static int numberOfFailures = 0;
@GET
public void asyncGet(@Suspended AsyncResponse asyncResponse) {
asyncResponse.register((CompletionCallback)(t) ->{
if(t == null){
numberOfSuccessResponse++;
}else{
numberOfFailures++;
}
System.out.println("Success: " + numberOfSuccessResponse + "/ Failure: " + numberOfFailures);
});
new Thread(() -> {
try{
randomException();
int sleepMillis = sleep();
log("runnable thread end.");
Response response = Response.ok("Success (" + sleepMillis + ")").build();
asyncResponse.resume(response);
}catch(RuntimeException e){
asyncResponse.resume(e);
}
}).start();
log("server thread end.");
}
private void randomException() {
if(new Random().nextInt(2) % 2 == 0) throw new RuntimeException();
}
private int sleep() {
try {
int millis = new Random().nextInt(5) * 1000;
log("sleep :" + millis);
Thread.sleep(millis);
return millis;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void log(String message) {
System.out.println(message
+ " / " + Thread.currentThread().getId()
+ " / " + Thread.currentThread().getName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment