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