• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 
17 package com.android.server.art;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 
22 import java.util.concurrent.ScheduledExecutorService;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.function.Supplier;
26 
27 /**
28  * A class that executes commands with a minimum interval.
29  *
30  * @hide
31  */
32 public class Debouncer {
33     @NonNull private Supplier<ScheduledExecutorService> mScheduledExecutorFactory;
34     private final long mIntervalMs;
35     @Nullable private ScheduledFuture<?> mCurrentTask = null;
36 
Debouncer( long intervalMs, @NonNull Supplier<ScheduledExecutorService> scheduledExecutorFactory)37     public Debouncer(
38             long intervalMs, @NonNull Supplier<ScheduledExecutorService> scheduledExecutorFactory) {
39         mScheduledExecutorFactory = scheduledExecutorFactory;
40         mIntervalMs = intervalMs;
41     }
42 
43     /**
44      * Runs the given command after the interval has passed. If another command comes in during
45      * this interval, the previous one will never run.
46      */
maybeRunAsync(@onNull Runnable command)47     synchronized public void maybeRunAsync(@NonNull Runnable command) {
48         if (mCurrentTask != null) {
49             mCurrentTask.cancel(false /* mayInterruptIfRunning */);
50         }
51         ScheduledExecutorService executor = mScheduledExecutorFactory.get();
52         mCurrentTask = executor.schedule(command, mIntervalMs, TimeUnit.MILLISECONDS);
53         executor.shutdown();
54     }
55 }
56