|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +package org.elasticsearch.common.util.concurrent; |
| 20 | + |
| 21 | +import org.apache.logging.log4j.Logger; |
| 22 | +import org.apache.logging.log4j.message.ParameterizedMessage; |
| 23 | +import org.elasticsearch.common.unit.TimeValue; |
| 24 | +import org.elasticsearch.threadpool.ThreadPool; |
| 25 | + |
| 26 | +import java.io.Closeable; |
| 27 | +import java.util.Objects; |
| 28 | +import java.util.concurrent.ScheduledFuture; |
| 29 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 30 | + |
| 31 | +/** |
| 32 | + * A base class for tasks that need to repeat. |
| 33 | + */ |
| 34 | +public abstract class AbstractAsyncTask implements Runnable, Closeable { |
| 35 | + |
| 36 | + private final Logger logger; |
| 37 | + private final ThreadPool threadPool; |
| 38 | + private final AtomicBoolean closed = new AtomicBoolean(false); |
| 39 | + private final boolean autoReschedule; |
| 40 | + private volatile ScheduledFuture<?> scheduledFuture; |
| 41 | + private volatile boolean isScheduledOrRunning; |
| 42 | + private volatile Exception lastThrownException; |
| 43 | + private volatile TimeValue interval; |
| 44 | + |
| 45 | + protected AbstractAsyncTask(Logger logger, ThreadPool threadPool, TimeValue interval, boolean autoReschedule) { |
| 46 | + this.logger = logger; |
| 47 | + this.threadPool = threadPool; |
| 48 | + this.interval = interval; |
| 49 | + this.autoReschedule = autoReschedule; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Change the interval between runs. |
| 54 | + * If a future run is scheduled then this will reschedule it. |
| 55 | + * @param interval The new interval between runs. |
| 56 | + */ |
| 57 | + public synchronized void setInterval(TimeValue interval) { |
| 58 | + this.interval = interval; |
| 59 | + if (scheduledFuture != null) { |
| 60 | + rescheduleIfNecessary(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public TimeValue getInterval() { |
| 65 | + return interval; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Test any external conditions that determine whether the task |
| 70 | + * should be scheduled. This method does *not* need to test if |
| 71 | + * the task is closed, as being closed automatically prevents |
| 72 | + * scheduling. |
| 73 | + * @return Should the task be scheduled to run? |
| 74 | + */ |
| 75 | + protected abstract boolean mustReschedule(); |
| 76 | + |
| 77 | + /** |
| 78 | + * Schedule the task to run after the configured interval if it |
| 79 | + * is not closed and any further conditions imposed by derived |
| 80 | + * classes are met. Any previously scheduled invocation is |
| 81 | + * cancelled. |
| 82 | + */ |
| 83 | + public synchronized void rescheduleIfNecessary() { |
| 84 | + if (isClosed()) { |
| 85 | + return; |
| 86 | + } |
| 87 | + if (scheduledFuture != null) { |
| 88 | + FutureUtils.cancel(scheduledFuture); |
| 89 | + } |
| 90 | + if (interval.millis() > 0 && mustReschedule()) { |
| 91 | + if (logger.isTraceEnabled()) { |
| 92 | + logger.trace("scheduling {} every {}", toString(), interval); |
| 93 | + } |
| 94 | + scheduledFuture = threadPool.schedule(interval, getThreadPool(), this); |
| 95 | + isScheduledOrRunning = true; |
| 96 | + } else { |
| 97 | + logger.trace("scheduled {} disabled", toString()); |
| 98 | + scheduledFuture = null; |
| 99 | + isScheduledOrRunning = false; |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + public boolean isScheduled() { |
| 104 | + // Currently running counts as scheduled to avoid an oscillating return value |
| 105 | + // from this method when a task is repeatedly running and rescheduling itself. |
| 106 | + return isScheduledOrRunning; |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Cancel any scheduled run, but do not prevent subsequent restarts. |
| 111 | + */ |
| 112 | + public synchronized void cancel() { |
| 113 | + FutureUtils.cancel(scheduledFuture); |
| 114 | + scheduledFuture = null; |
| 115 | + isScheduledOrRunning = false; |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Cancel any scheduled run |
| 120 | + */ |
| 121 | + @Override |
| 122 | + public synchronized void close() { |
| 123 | + if (closed.compareAndSet(false, true)) { |
| 124 | + cancel(); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + public boolean isClosed() { |
| 129 | + return this.closed.get(); |
| 130 | + } |
| 131 | + |
| 132 | + @Override |
| 133 | + public final void run() { |
| 134 | + synchronized (this) { |
| 135 | + scheduledFuture = null; |
| 136 | + isScheduledOrRunning = autoReschedule; |
| 137 | + } |
| 138 | + try { |
| 139 | + runInternal(); |
| 140 | + } catch (Exception ex) { |
| 141 | + if (lastThrownException == null || sameException(lastThrownException, ex) == false) { |
| 142 | + // prevent the annoying fact of logging the same stuff all the time with an interval of 1 sec will spam all your logs |
| 143 | + logger.warn( |
| 144 | + () -> new ParameterizedMessage( |
| 145 | + "failed to run task {} - suppressing re-occurring exceptions unless the exception changes", |
| 146 | + toString()), |
| 147 | + ex); |
| 148 | + lastThrownException = ex; |
| 149 | + } |
| 150 | + } finally { |
| 151 | + if (autoReschedule) { |
| 152 | + rescheduleIfNecessary(); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + private static boolean sameException(Exception left, Exception right) { |
| 158 | + if (left.getClass() == right.getClass()) { |
| 159 | + if (Objects.equals(left.getMessage(), right.getMessage())) { |
| 160 | + StackTraceElement[] stackTraceLeft = left.getStackTrace(); |
| 161 | + StackTraceElement[] stackTraceRight = right.getStackTrace(); |
| 162 | + if (stackTraceLeft.length == stackTraceRight.length) { |
| 163 | + for (int i = 0; i < stackTraceLeft.length; i++) { |
| 164 | + if (stackTraceLeft[i].equals(stackTraceRight[i]) == false) { |
| 165 | + return false; |
| 166 | + } |
| 167 | + } |
| 168 | + return true; |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | + return false; |
| 173 | + } |
| 174 | + |
| 175 | + protected abstract void runInternal(); |
| 176 | + |
| 177 | + /** |
| 178 | + * Use the same threadpool by default. |
| 179 | + * Derived classes can change this if required. |
| 180 | + */ |
| 181 | + protected String getThreadPool() { |
| 182 | + return ThreadPool.Names.SAME; |
| 183 | + } |
| 184 | +} |
0 commit comments