Last active
August 29, 2015 14:15
-
-
Save murayama333/418b0eabfa4640644611 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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