Imported vpnservice as a subtree
[netvirt.git] / vpnservice / mdsalutil / mdsalutil-api / src / main / java / org / opendaylight / vpnservice / datastoreutils / TaskRetryLooper.java
1 /*
2  * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.vpnservice.datastoreutils;
10
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 import java.util.concurrent.Callable;
15
16 public class TaskRetryLooper {
17     private static final Logger LOG = LoggerFactory.getLogger(TaskRetryLooper.class);
18
19     private final long tick;
20     private final int maxRetries;
21
22     /**
23      * @param tick       sleep between steps in miliseconds
24      * @param maxRetries retries limit
25      */
26     public TaskRetryLooper(long tick, int maxRetries) {
27         this.tick = tick;
28         this.maxRetries = maxRetries;
29     }
30
31     public <T> T loopUntilNoException(Callable<T> task) throws Exception {
32         T output = null;
33
34         Exception taskException = null;
35         for (int i = 0; i < maxRetries; i++) {
36             taskException = null;
37             try {
38                 output = task.call();
39                 break;
40             } catch (Exception exception) {
41                 LOG.debug("looper step failed: {}", exception.getMessage());
42                 taskException = exception;
43             }
44
45             try {
46                 Thread.sleep(tick);
47             } catch (InterruptedException e) {
48                 LOG.debug("interrupted: {}", e.getMessage(), e);
49             }
50         }
51
52         if (taskException != null) {
53             throw taskException;
54         }
55
56         LOG.debug("looper step succeeded: {}", output);
57         return output;
58     }
59 }