mvn clean install tomee:run
MicroProfile Fault Tolerance - Timeout
This is an example of how to use Microprofile @Timeout in TomEE.
Timeout Feature
Fault Tolerance Timeout allow to specify how long a task can take to complete its execution and aborting it
in case of timeout. Timeout feature can be used along with other annotations to guide the execution and result of a task.
Check the
specification
for more details.
Timeout annotation allows to configure :
-
value: the timeout value
-
unit: the timeout unit
Example
Run the application
How does it work?
The method statusOfDayByAccuWeather
fails when the threshold of @Timeout
annotation is reached due to a long execution of
longProcessingTask
method. To respond to the request nicely, a fallback method will take place to complete the request
successfully. The fallback method is determined by @Fallback annotation.
@RequestScoped
public class WeatherGateway {
private static final Logger LOGGER = Logger.getLogger(WeatherGateway.class.getName());
@Timeout(50)
@Fallback(fallbackMethod = "statusOfWeekByMetEireann")
public String statusOfDayByAccuWeather(){
return longProcessingTask();
}
public String statusOfWeekByMetEireann(){
LOGGER.log(Level.WARNING, "MetEireann backup service has been requested due to AccuWeather timeout");
return "Beautiful day";
}
private String longProcessingTask(){
try {
Thread.sleep(80);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"AccuWeather task has been interrupted.");
}
return null;
}
...
}
Day status call
GET http://localhost:8080/mp-faulttolerance-timeout/weather/day/status
Server log
WARNING AccuWeather task has been interrupted.
WARNING MetEireann fallback service has been requested due to AccuWeather timeout.
Response
Beautiful day!
Running the test
You can also try it out using the WeatherServiceTest.java available in the project.
mvn clean test
[INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0