Mike Ma | 69d8b3e | 2018-02-23 14:51:26 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2017 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.internal.os; |
| 18 | |
| 19 | import android.annotation.Nullable; |
| 20 | import android.os.SystemClock; |
| 21 | import android.util.Slog; |
| 22 | |
| 23 | /** |
| 24 | * The base class of all KernelUidCpuTimeReaders. |
| 25 | * |
| 26 | * This class is NOT designed to be thread-safe or accessed by more than one caller (due to |
| 27 | * the nature of {@link #readDelta(Callback)}). |
| 28 | */ |
| 29 | public abstract class KernelUidCpuTimeReaderBase<T extends KernelUidCpuTimeReaderBase.Callback> { |
| 30 | protected static final boolean DEBUG = false; |
| 31 | // Throttle interval in milliseconds |
| 32 | private static final long DEFAULT_THROTTLE_INTERVAL = 10_000L; |
| 33 | |
| 34 | private final String TAG = this.getClass().getSimpleName(); |
| 35 | private long mLastTimeReadMs = Long.MIN_VALUE; |
| 36 | private long mThrottleInterval = DEFAULT_THROTTLE_INTERVAL; |
| 37 | |
| 38 | // A generic Callback interface (used by readDelta) to be extended by subclasses. |
| 39 | public interface Callback { |
| 40 | } |
| 41 | |
| 42 | public void readDelta(@Nullable T cb) { |
| 43 | if (SystemClock.elapsedRealtime() < mLastTimeReadMs + mThrottleInterval) { |
| 44 | if (DEBUG) { |
| 45 | Slog.d(TAG, "Throttle"); |
| 46 | } |
| 47 | return; |
| 48 | } |
| 49 | readDeltaImpl(cb); |
| 50 | mLastTimeReadMs = SystemClock.elapsedRealtime(); |
| 51 | } |
| 52 | |
| 53 | protected abstract void readDeltaImpl(@Nullable T cb); |
| 54 | |
| 55 | public void setThrottleInterval(long throttleInterval) { |
| 56 | if (throttleInterval >= 0) { |
| 57 | mThrottleInterval = throttleInterval; |
| 58 | } |
| 59 | } |
| 60 | } |