samples/privilegedcreator/test/api/MutexTest.java
author jaroslav.tulach@apidesign.org
Mon, 25 May 2009 21:49:25 +0200
changeset 334 0f3e13581901
parent 332 139aacf8152d
permissions -rw-r--r--
Use the MUTEX variable instead of local lock
     1 package api;
     2 
     3 import org.apidesign.privileged.api.Mutex;
     4 import org.junit.After;
     5 import org.junit.AfterClass;
     6 import org.junit.Before;
     7 import org.junit.BeforeClass;
     8 import org.junit.Test;
     9 import static org.junit.Assert.*;
    10 
    11 public class MutexTest {
    12     // BEGIN: mutex.init
    13     private static final Mutex.Privileged PRIVILEGED = new Mutex.Privileged();
    14     public static final Mutex MUTEX = new Mutex(PRIVILEGED);
    15     // END: mutex.init
    16 
    17     public MutexTest() {
    18     }
    19 
    20     /**
    21      * Test of readAccess method, of class Mutex.
    22      */
    23     @Test
    24     public void readAccess() {
    25         // BEGIN: mutex.use
    26         class R implements Runnable {
    27             int cnt;
    28             
    29             public void run() {
    30                 cnt++;
    31             }
    32         }
    33         R r = new R();
    34         MUTEX.readAccess(r);
    35         assertEquals("Counter increased", 1, r.cnt);
    36         // END: mutex.use
    37     }
    38     
    39     @Test
    40     public void usePrivileged() {
    41         int cnt = 0;
    42         // BEGIN: mutex.privileged
    43         PRIVILEGED.enterReadAccess();
    44         try {
    45           // do the operation
    46             cnt++;
    47         } finally {
    48            PRIVILEGED.exitReadAccess();
    49         }
    50         assertEquals("Counter increased", 1, cnt);
    51         // END: mutex.privileged
    52         
    53     }
    54 
    55 }