blob: 17965d099af0cb6262dcff28fcc7400069c9be20 [file] [log] [blame]
Jorim Jaggi36db1272017-03-28 00:43:31 +02001/*
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
17package com.android.server;
18
19import android.os.Process;
20
21/**
22 * Utility class to boost threads in sections where important locks are held.
23 */
24public class ThreadPriorityBooster {
25
26 private final int mBoostToPriority;
27 private final int mLockGuardIndex;
28
29 private final ThreadLocal<PriorityState> mThreadState = new ThreadLocal<PriorityState>() {
30 @Override protected PriorityState initialValue() {
31 return new PriorityState();
32 }
33 };
34
35 public ThreadPriorityBooster(int boostToPriority, int lockGuardIndex) {
36 mBoostToPriority = boostToPriority;
37 mLockGuardIndex = lockGuardIndex;
38 }
39
40 public void boost() {
41 final int tid = Process.myTid();
42 final int prevPriority = Process.getThreadPriority(tid);
43 PriorityState state = mThreadState.get();
44 if (state.regionCounter == 0 && prevPriority > mBoostToPriority) {
45 state.prevPriority = prevPriority;
46 Process.setThreadPriority(tid, mBoostToPriority);
47 }
48 state.regionCounter++;
49 if (LockGuard.ENABLED) {
50 LockGuard.guard(mLockGuardIndex);
51 }
52 }
53
54 public void reset() {
55 PriorityState state = mThreadState.get();
56 state.regionCounter--;
57 if (state.regionCounter == 0 && state.prevPriority > mBoostToPriority) {
58 Process.setThreadPriority(Process.myTid(), state.prevPriority);
59 }
60 }
61
62 private static class PriorityState {
63
64 /**
65 * Acts as counter for number of synchronized region that needs to acquire 'this' as a lock
66 * the current thread is currently in. When it drops down to zero, we will no longer boost
67 * the thread's priority.
68 */
69 int regionCounter;
70
71 /**
72 * The thread's previous priority before boosting.
73 */
74 int prevPriority;
75 }
76}