BUG-8607: Fix issues in checkstyle enforcement for module
[openflowplugin.git] / openflowplugin-common / src / main / java / org / opendaylight / openflowplugin / common / wait / SimpleTaskRetryLooper.java
1 /*
2  * Copyright (c) 2015, 2017 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 final Logger LOG = LoggerFactory.getLogger(SimpleTaskRetryLooper.class);
21
22     private final long tick;
23     private final int maxRetries;
24
25     /**
26      * It retries the task passed to its method loopUntilNoException a number of
27      * times (maxRetries).
28      *
29      * @param tick
30      *            sleep between steps in miliseconds
31      * @param maxRetries
32      *            retries limit
33      */
34     public SimpleTaskRetryLooper(long tick, int maxRetries) {
35         this.tick = tick;
36         this.maxRetries = maxRetries;
37     }
38
39     @SuppressWarnings("checkstyle:IllegalCatch")
40     public <T> T loopUntilNoException(Callable<T> task) throws Exception {
41         T output = null;
42
43         Exception taskException = null;
44         for (int i = 0; i < maxRetries; i++) {
45             taskException = null;
46             try {
47                 output = task.call();
48                 break;
49             } catch (Exception exception) {
50                 LOG.debug("looper step failed: {}", exception.getMessage());
51                 taskException = exception;
52             }
53
54             try {
55                 Thread.sleep(tick);
56             } catch (InterruptedException e) {
57                 LOG.debug("interrupted: {}", e.getMessage(), e);
58                 Thread.currentThread().interrupt();
59             }
60         }
61
62         if (taskException != null) {
63             throw taskException;
64         }
65
66         LOG.debug("looper step succeeded: {}", output);
67         return output;
68     }
69 }