001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc.test;
005:
006: import EDU.oswego.cs.dl.util.concurrent.CyclicBarrier;
007:
008: public class BitChangeNotReflected extends TCTestCase {
009:
010: private static final byte INITIAL = 0x01;
011: private static final int LOOP_COUNT = 50000;
012:
013: public void testBitChangeNotReflected() throws Exception {
014: BitData data = new BitData();
015: Object lock = new Object();
016: CyclicBarrier barrier = new CyclicBarrier(2);
017: Thread t1 = new Changer(data, lock, barrier);
018: Thread t2 = new Reader(data, lock, barrier);
019: t1.start();
020: t2.start();
021: try {
022: t1.join();
023: t2.join();
024: } catch (InterruptedException e) {
025: throw new RuntimeException(e);
026: }
027: }
028:
029: public static byte shiftRightRotate(byte f) {
030: byte f1 = (byte) (f >> 1);
031: return (byte) (f1 == 0x00 ? 0x80 : f1);
032: }
033:
034: static class Changer extends Thread {
035:
036: private final BitData data;
037: private final Object lock;
038: private final CyclicBarrier barrier;
039:
040: public Changer(BitData data, Object lock, CyclicBarrier barrier) {
041: this .data = data;
042: this .lock = lock;
043: this .barrier = barrier;
044: }
045:
046: public void run() {
047: try {
048: run2();
049: } catch (Exception e) {
050: throw new RuntimeException(e);
051: }
052: }
053:
054: public void run2() throws Exception {
055: int count = LOOP_COUNT;
056: while (count-- > 0) {
057: barrier.barrier();
058: synchronized (lock) {
059: data.shiftRightRotate();
060: }
061: }
062: }
063:
064: }
065:
066: static class Reader extends Thread {
067:
068: private final BitData data;
069: private final Object lock;
070: private final CyclicBarrier barrier;
071:
072: public Reader(BitData data, Object lock, CyclicBarrier barrier) {
073: this .data = data;
074: this .lock = lock;
075: this .barrier = barrier;
076: }
077:
078: public void run() {
079: try {
080: run2();
081: } catch (Exception e) {
082: throw new RuntimeException(e);
083: }
084: }
085:
086: public void run2() throws Exception {
087: byte local = INITIAL;
088: int count = LOOP_COUNT;
089: while (count-- > 0) {
090: local = shiftRightRotate(local);
091: synchronized (lock) {
092: data.isEqual(local);
093: }
094: barrier.barrier();
095: }
096:
097: }
098:
099: }
100:
101: static class BitData {
102: int i;
103: byte flag = INITIAL;
104:
105: void shiftRightRotate() {
106: flag = BitChangeNotReflected.shiftRightRotate(flag);
107: }
108:
109: boolean isEqual(byte f) {
110: return (flag == f);
111: }
112:
113: byte getFlag() {
114: return flag;
115: }
116:
117: }
118:
119: }
|