blob: 756abdd4621da692a37f52c2424d84f832551748 [file] [log] [blame]
Jonathan Hart54119bb2016-02-06 18:48:27 -08001/*
2 * Copyright 2016 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onlab.util;
18
19import org.slf4j.Logger;
20import org.slf4j.LoggerFactory;
21
22/**
23 * Wrapper for a recurring task which catches all exceptions to prevent task
24 * being suppressed in a ScheduledExecutorService.
25 */
26public final class SafeRecurringTask implements Runnable {
27
28 private static final Logger log = LoggerFactory.getLogger(SafeRecurringTask.class);
29
30 private final Runnable runnable;
31
32 /**
33 * Constructor.
34 *
35 * @param runnable runnable to wrap
36 */
37 private SafeRecurringTask(Runnable runnable) {
38 this.runnable = runnable;
39 }
40
41 @Override
42 public void run() {
43 if (Thread.currentThread().isInterrupted()) {
44 log.info("Task interrupted, quitting");
45 return;
46 }
47
48 try {
49 runnable.run();
50 } catch (Exception e) {
51 // Catch all exceptions to avoid task being suppressed
52 log.error("Exception thrown during task", e);
53 }
54 }
55
56 /**
57 * Wraps a runnable in a safe recurring task.
58 *
59 * @param runnable runnable to wrap
60 * @return safe recurring task
61 */
62 public static SafeRecurringTask wrap(Runnable runnable) {
63 return new SafeRecurringTask(runnable);
64 }
65
66}