1 /* 2 * Copyright (C) 2018 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.bips.util; 18 19 import java.util.ArrayList; 20 import java.util.Collections; 21 import java.util.List; 22 23 /** 24 * A lock that always allows higher-priority attempts to receive the lock first 25 */ 26 public class PriorityLock { 27 private boolean mLocked = false; 28 private List<Integer> mPriorities = new ArrayList<>(); 29 30 /** 31 * Return when locked, always giving priority to the highest priority lock request 32 */ lock(int priority)33 public synchronized void lock(int priority) throws InterruptedException { 34 if (mLocked) { 35 mPriorities.add(priority); 36 Collections.sort(mPriorities); 37 try { 38 while (mLocked || priority < mPriorities.get(mPriorities.size() - 1)) { 39 wait(); 40 } 41 } finally { 42 mPriorities.remove((Integer) priority); 43 } 44 } 45 mLocked = true; 46 } 47 48 /** 49 * Unlock this object (when it is already locked) 50 */ unlock()51 public synchronized void unlock() { 52 if (!mLocked) { 53 throw new IllegalArgumentException("not locked"); 54 } 55 mLocked = false; 56 notifyAll(); 57 } 58 } 59