1 /* 2 * Copyright (C) 2008 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 package android.os.cts; 17 18 import junit.framework.TestCase; 19 20 import android.os.ConditionVariable; 21 22 import com.android.compatibility.common.util.TestThread; 23 24 public class ConditionVariableTest extends TestCase { 25 private static final int WAIT_TIME = 3000; 26 private static final int BLOCK_TIME = 1000; 27 private static final int BLOCK_TIME_DELTA = 200; 28 private static final int SLEEP_TIME = 1000; 29 private static final int TOLERANCE_MS = BLOCK_TIME; 30 private ConditionVariable mConditionVariable; 31 32 @Override 33 protected void setUp() throws Exception { 34 super.setUp(); 35 mConditionVariable = new ConditionVariable(); 36 } 37 38 public void testConstructor() { 39 assertFalse(mConditionVariable.block(BLOCK_TIME)); 40 assertFalse(new ConditionVariable(false).block(BLOCK_TIME)); 41 assertTrue(new ConditionVariable(true).block(BLOCK_TIME)); 42 } 43 44 public void testConditionVariable() throws Throwable { 45 // test open then block(long) 46 mConditionVariable.open(); 47 long time = System.currentTimeMillis(); 48 assertTrue(mConditionVariable.block(BLOCK_TIME)); 49 assertTrue(System.currentTimeMillis() - time < TOLERANCE_MS); 50 51 // test close then block(long) 52 mConditionVariable.close(); 53 time = System.currentTimeMillis(); 54 assertFalse(mConditionVariable.block(BLOCK_TIME)); 55 assertTrue(System.currentTimeMillis() - time >= BLOCK_TIME); 56 57 // test block then open 58 time = System.currentTimeMillis(); 59 TestThread t = new TestThread(new Runnable() { 60 61 public void run() { 62 try { 63 Thread.sleep(SLEEP_TIME); 64 } catch (InterruptedException e) { 65 fail(e.getMessage()); 66 } 67 mConditionVariable.open(); 68 } 69 }); 70 71 t.start(); 72 mConditionVariable.block(); 73 long timeDelta = System.currentTimeMillis() - time; 74 assertTrue(timeDelta >= BLOCK_TIME && timeDelta <= BLOCK_TIME + BLOCK_TIME_DELTA); 75 t.joinAndCheck(WAIT_TIME); 76 77 time = System.currentTimeMillis(); 78 t = new TestThread(new Runnable() { 79 80 public void run() { 81 try { 82 Thread.sleep(BLOCK_TIME >> 1); 83 } catch (InterruptedException e) { 84 fail(e.getMessage()); 85 } 86 mConditionVariable.open(); 87 } 88 }); 89 t.start(); 90 91 assertTrue(mConditionVariable.block(BLOCK_TIME)); 92 t.joinAndCheck(WAIT_TIME); 93 } 94 } 95