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 art; 18 19 public class Test1933 { run()20 public static void run() throws Exception { 21 System.out.println("No contention"); 22 testNoContention(new Monitors.NamedLock("test testNoContention")); 23 24 System.out.println("Normal contended monitor"); 25 testNormalContendedMonitor(new Monitors.NamedLock("test testNormalContendedMonitor")); 26 27 System.out.println("Waiting on a monitor"); 28 testNormalWaitMonitor(new Monitors.NamedLock("test testNormalWaitMonitor")); 29 } 30 testNormalWaitMonitor(final Monitors.NamedLock lk)31 public static void testNormalWaitMonitor(final Monitors.NamedLock lk) throws Exception { 32 final Monitors.LockController controller1 = new Monitors.LockController(lk); 33 controller1.DoLock(); 34 controller1.waitForLockToBeHeld(); 35 controller1.DoWait(); 36 controller1.waitForNotifySleep(); 37 // Spurious wakeups can hurt us here. Just retry until we get the result we expect. The test 38 // will timeout eventually. 39 Object mon = controller1.getWorkerContendedMonitor(); 40 for (; mon == null; mon = controller1.getWorkerContendedMonitor()) { Thread.yield(); } 41 System.out.println("c1 is contending for monitor: " + mon); 42 synchronized (lk) { 43 lk.DoNotifyAll(); 44 } 45 controller1.DoUnlock(); 46 } 47 testNormalContendedMonitor(final Monitors.NamedLock lk)48 public static void testNormalContendedMonitor(final Monitors.NamedLock lk) throws Exception { 49 final Monitors.LockController controller1 = new Monitors.LockController(lk); 50 final Monitors.LockController controller2 = new Monitors.LockController(lk); 51 controller1.DoLock(); 52 controller1.waitForLockToBeHeld(); 53 controller2.DoLock(); 54 controller2.waitForContendedSleep(); 55 System.out.println("c2 is contending for monitor: " + controller2.getWorkerContendedMonitor()); 56 controller1.DoUnlock(); 57 controller2.waitForLockToBeHeld(); 58 controller2.DoUnlock(); 59 } 60 testNoContention(final Monitors.NamedLock lk)61 public static void testNoContention(final Monitors.NamedLock lk) throws Exception { 62 synchronized (lk) { 63 System.out.println("current thread is contending for monitor: " + 64 Monitors.getCurrentContendedMonitor(null)); 65 } 66 } 67 } 68