samples/individualsamples/test/org/apidesign/samples/StringBufferTest.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 20:46:27 +0100
changeset 408 9a439a79c6d0
permissions -rw-r--r--
Use scala 2.10.4 to compile on JDK8
     1 package org.apidesign.samples;
     2 
     3 import java.util.logging.Level;
     4 import java.util.logging.Logger;
     5 import org.junit.After;
     6 import org.junit.AfterClass;
     7 import org.junit.Before;
     8 import org.junit.BeforeClass;
     9 import org.junit.Test;
    10 import static org.junit.Assert.*;
    11 
    12 public class StringBufferTest {
    13     @Test
    14     public void createRegular() {
    15         StringBuffer sb = new StringBuffer();
    16         assertAddAndToString(sb);
    17     }
    18 
    19     @Test
    20     public void createUnsynchronized() throws InterruptedException {
    21         final StringBuffer sb = StringBuffer.createUnsynchronized();
    22         
    23         class Lock extends Thread {
    24             int state;
    25             
    26             @Override
    27             public void run() {
    28                 synchronized (sb) {
    29                     try {
    30                         state = 1;
    31                         sb.notifyAll();
    32                         sb.wait();
    33                         state = 2;
    34                     } catch (InterruptedException ex) {
    35                         Logger.getLogger(StringBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    36                     }
    37                 }
    38             }
    39             
    40             public void waitLocked() throws InterruptedException {
    41                 synchronized (sb) {
    42                     for (;;) {
    43                         if (state == 1) {
    44                             return;
    45                         }
    46                         sb.wait();
    47                     }
    48                 }
    49             }
    50         }
    51         Lock lock = new Lock();
    52         lock.start();
    53         lock.waitLocked();
    54         
    55         assertEquals("result is really locked", 1, lock.state);
    56         
    57         assertAddAndToString(sb);
    58         
    59         assertEquals("result is still locked", 1, lock.state);
    60     }
    61 
    62     private void assertAddAndToString(StringBuffer sb) {
    63         sb.append("Hello").append(" ");
    64         sb.append("API").append(" Design!");
    65         
    66         assertEquals("Hello API Design!", sb.toString());
    67     }
    68 
    69 }