introduction of ofp-common
[openflowplugin.git] / openflowplugin-common / src / main / java / org / opendaylight / openflowplugin / common / wait / SimpleTaskRetryLooper.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. 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.openflowplugin.common.wait;
10
11 import java.util.concurrent.Callable;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 /**
16  * Created by mirehak on 4/28/15.
17  */
18 public class SimpleTaskRetryLooper {
19
20     private static Logger LOG = LoggerFactory.getLogger(SimpleTaskRetryLooper.class);
21
22     private final long tick;
23     private final int maxRetries;
24
25     /**
26      * @param tick       sleep between steps in miliseconds
27      * @param maxRetries retries limit
28      */
29     public SimpleTaskRetryLooper(long tick, int maxRetries) {
30         this.tick = tick;
31         this.maxRetries = maxRetries;
32     }
33
34     public <T> T loopUntilNoException(Callable<T> task) throws Exception {
35         T output = null;
36
37         Exception taskException = null;
38         for (int i = 0; i < maxRetries; i++) {
39             taskException = null;
40             try {
41                 output = task.call();
42                 break;
43             } catch (Exception exception) {
44                 LOG.debug("looper step failed: {}", exception.getMessage());
45                 taskException = exception;
46             }
47
48             try {
49                 Thread.sleep(tick);
50             } catch (InterruptedException e) {
51                 LOG.debug("interrupted: {}", e.getMessage(), e);
52             }
53         }
54
55         if (taskException != null) {
56             throw taskException;
57         }
58
59         return output;
60     }
61 }