Java Retry implement
There are many cases in which you may wish to retry an operation a certain number of times. Examples are database failures, network communication failures or file IO problems.
Approach 1
This is the traditional approach and involves a counter and a loop.
final int numberOfRetries = 5 ; final long timeToWait = 1000 ; for ( int i= 0 ; i<numberOfRetries; i++) { //perform the operation try { break ; } catch (Exception e) { logger.error( "Retrying..." ,e); try { Thread.sleep(timeToWait); } catch (InterruptedException i) { } } } |
Approach 2
In this approach, we hide the retry counter in a separate class called RetryStrategy
and call it like this:
public class RetryStrategy { public static final int DEFAULT_NUMBER_OF_RETRIES = 5 ; public static final long DEFAULT_WAIT_TIME = 1000 ; private int numberOfRetries; //total number of tries private int numberOfTriesLeft; //number left private long timeToWait; //wait interval public RetryStrategy() { this (DEFAULT_NUMBER_OF_RETRIES, DEFAULT_WAIT_TIME); } public RetryStrategy( int numberOfRetries, long timeToWait) { this .numberOfRetries = numberOfRetries; numberOfTriesLeft = numberOfRetries; this .timeToWait = timeToWait; } /** * @return true if there are tries left */ public boolean shouldRetry() { return numberOfTriesLeft > 0 ; } /** * This method should be called if a try fails. * * @throws RetryException if there are no more tries left */ public void errorOccured() throws RetryException { numberOfTriesLeft --; if (!shouldRetry()) { throw new RetryException(numberOfRetries + " attempts to retry failed at " + getTimeToWait() + "ms interval" ); } waitUntilNextTry(); } /** * @return time period between retries */ public long getTimeToWait() { return timeToWait ; } /** * Sleeps for the duration of the defined interval */ private void waitUntilNextTry() { try { Thread.sleep(getTimeToWait()); } catch (InterruptedException ignored) {} } public static void main(String[] args) { RetryStrategy retry = new RetryStrategy(); while (retry.shouldRetry()) { try { break ; } catch (Exception e) { try { retry.errorOccured(); } catch (RetryException e1) { e.printStackTrace(); } } } } } |
Approach 3
Approach 2, although cleaner, hasn't really reduced the number of lines of code we have to write. In the next approach, we hide the retry loop and all logic in a separate class called RetriableTask
. We make the operation that we are going to retry Callable
and wrap it in a RetriableTask
which then handles all the retrying for us, behind-the-scenes:
public class RetriableTask<T> implements Callable<T> { private Callable<T> task; public static final int DEFAULT_NUMBER_OF_RETRIES = 5 ; public static final long DEFAULT_WAIT_TIME = 1000 ; private int numberOfRetries; // total number of tries private int numberOfTriesLeft; // number left private long timeToWait; // wait interval public RetriableTask(Callable<T> task) { this (DEFAULT_NUMBER_OF_RETRIES, DEFAULT_WAIT_TIME, task); } public RetriableTask( int numberOfRetries, long timeToWait, Callable<T> task) { this .numberOfRetries = numberOfRetries; numberOfTriesLeft = numberOfRetries; this .timeToWait = timeToWait; this .task = task; } public T call() throws Exception { while ( true ) { try { return task.call(); } catch (InterruptedException e) { throw e; } catch (CancellationException e) { throw e; } catch (Exception e) { numberOfTriesLeft--; if (numberOfTriesLeft == 0 ) { throw new RetryException(numberOfRetries + " attempts to retry failed at " + timeToWait + "ms interval" , e); } Thread.sleep(timeToWait); } } } public static void main(String[] args) { Callable<Remote> task = new Callable<Remote>() { public Remote call() throws Exception { return (Remote) Naming.lookup(url); } }; RetriableTask<Remote> r = new RetriableTask<Remote>(task); try { r.call(); } catch (Exception e) { e.printStackTrace(); } } } |
Also see:
References:
Java Retry implement的更多相关文章
- java retry:详解
发现 今天在探秘线程池原理知识点,在阅读JDK源码时遇到程序代码中出现如下代码,因为之前没有遇到过,于是特地记录下来并谷歌了一番,后面我自己做了一些简要的验证和分析. 验证 网上溜达一番发现,这ret ...
- Effective Java 74 Implement Serializable judiciously
Disadvantage of Serializable A major cost of implementing Serializable is that it decreases the flex ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- Java Algorithm Problems
Java Algorithm Problems 程序员的一天 从开始这个Github已经有将近两年时间, 很高兴这个repo可以帮到有需要的人. 我一直认为, 知识本身是无价的, 因此每逢闲暇, 我就 ...
- 为什么Java中的String是设计成不可变的?(Why String is immutable in java)
There are many reasons due to the string class has been made immutable in Java. These reasons in vie ...
- 更好的 java 重试框架 sisyphus 入门简介
What is Sisyphus sisyphus 综合了 spring-retry 和 gauva-retrying 的优势,使用起来也非常灵活. 为什么选择这个名字 我觉得重试做的事情和西西弗斯很 ...
- Jmeter3.0新特性
2016-5-19昨日,Jmeter又更新了新版本. 那么新版本有哪些新特性呢? Changes This page details the changes made in the current ...
- jackson官方快速入门文档
官方地址: http://jackson.codehaus.org/ http://wiki.fasterxml.com/JacksonInFiveMinutes http://wiki.faster ...
- Maven聚合与继承的实例讲解(二)
继续上一节讲Maven的内容,我们这个节继续讲Maven继承和聚合的其他内容. 现在我们新建一个实例来测试Maven有关于聚合的部分 测试开始 一.建立以pom为packaging的项目 ...
随机推荐
- C#中的SubString()的用法
先看语法: String.SubString(int index,int length) index:开始位置,从0开始 length:你要取的子字符串的长度 例子: using ...
- [Leetcode] first missing positve 缺失的第一个正数
Given an unsorted integer array, find the first missing positive integer. For example,Given[1,2,0]re ...
- 【BZOJ 1492】 [NOI2007]货币兑换Cash 斜率优化DP
先说一下斜率优化:这是一种经典的dp优化,是OI中利用数形结合的思想解决问题的典范,通常用于优化dp,有时候其他的一些决策优化也会用到,看待他的角度一般有两种,但均将决策看为二维坐标系上的点,并转化为 ...
- vector创建2维数组
以前我要建立一个二维数组,总是使用 int N=5, M=6; vector<vector<int> > Matrix(N); for(int i =0; i< Matr ...
- CSS3不遥远,几个特性你要知道
CSS是众所周知且应用广泛的网站样式语言,在它的版本三(CSS3)计划中,新增了一些能够节省时间的特性.尽管只有当前最新了浏览器版本才能支持这些 效果,但了解它们还是必须且很有趣味性的.CSS3中的5 ...
- watch用法小记
By francis_hao Jun 30,2017 watch:周期性的执行一个一个程序,并全屏显示输出 概述 watch [options] command 描述 watch重复的运 ...
- Educational Codeforces Round 56 (Rated for Div. 2) ABCD
题目链接:https://codeforces.com/contest/1093 A. Dice Rolling 题意: 有一个号数为2-7的骰子,现在有一个人他想扔到几就能扔到几,现在问需要扔多少次 ...
- UVA10480:Sabotage(最小割+输出)
Sabotage 题目链接:https://vjudge.net/problem/UVA-10480 Description: The regime of a small but wealthy di ...
- JavaScript 被忽视的细节
语句/表达式 换个角度理解语句(statemaents)和表达式(expressions):表达式不会改变程序的运行状态,而语句会.还有一种叫做表达式语句,可以理解为表达式和语句的交集,如({a:1} ...
- CSS选择器及CSS3新增选择器
转自:http://www.cnblogs.com/libingql/p/4375354.html 1. CSS1定义的选择器 选择器 类型 说明 E 类型选择器 选择指定类型的元素 E#id ID选 ...