ResettingDelayedExecutor.java revision 12f608f3d2089439a108788a1908941eea4277b9
1/*
2 * Copyright (C) 2014 The Android Open Source Project
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 com.android.camera.async;
18
19import java.util.concurrent.Executor;
20import java.util.concurrent.ScheduledExecutorService;
21import java.util.concurrent.ScheduledFuture;
22import java.util.concurrent.TimeUnit;
23
24/**
25 * An executor which executes with a delay, discarding pending executions such
26 * that at most one task is queued at any time.
27 */
28public class ResettingDelayedExecutor implements Executor, SafeCloseable {
29    private final ScheduledExecutorService mExecutor;
30    private final long mDelay;
31    private final TimeUnit mDelayUnit;
32    /**
33     * Lock for all mutable state: {@link #mLatestRunRequest} and
34     * {@link #mClosed}.
35     */
36    private final Object mLock;
37    private ScheduledFuture<?> mLatestRunRequest;
38    private boolean mClosed;
39
40    public ResettingDelayedExecutor(ScheduledExecutorService executor, long delay, TimeUnit
41            delayUnit) {
42        mExecutor = executor;
43        mDelay = delay;
44        mDelayUnit = delayUnit;
45        mLock = new Object();
46        mClosed = false;
47    }
48
49    @Override
50    public void execute(Runnable runnable) {
51        synchronized (mLock) {
52            if (mClosed) {
53                return;
54            }
55            // Cancel any existing, queued task before scheduling another.
56            if (mLatestRunRequest != null) {
57                boolean mayInterruptIfRunning = false;
58                mLatestRunRequest.cancel(mayInterruptIfRunning);
59            }
60            mLatestRunRequest = mExecutor.schedule(runnable, mDelay, mDelayUnit);
61        }
62    }
63
64    @Override
65    public void close() {
66        synchronized (mLock) {
67            if (mClosed) {
68                return;
69            }
70            mClosed = true;
71            mExecutor.shutdownNow();
72        }
73    }
74}
75