Advertisement
dig090

Word Tearing Example

Oct 16th, 2012
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. package com.j256;
  2.  
  3. public class WordTearingExample {
  4.  
  5.     private static final int NUM_THREADS = 100;
  6.     private static final int ITERS = 100000000;
  7.  
  8.     public static void main(String[] args) {
  9.         Thread[] threads = new Thread[NUM_THREADS];
  10.         byte[] counts = new byte[NUM_THREADS];
  11.         for (int i = 0; i < NUM_THREADS; ++i) {
  12.             threads[i] = new Thread(new Inner(counts, i));
  13.             threads[i].start();
  14.         }
  15.     }
  16.  
  17.     private static class Inner implements Runnable {
  18.  
  19.         private final byte[] counts;
  20.         private final int id;
  21.  
  22.         public Inner(byte[] counts, int id) {
  23.             this.counts = counts;
  24.             this.id = id;
  25.         }
  26.  
  27.         public void run() {
  28.             for (int i = 0; i < ITERS; i++) {
  29.                 if (counts[id] != (byte) i) {
  30.                     System.err.println("Word-Tearing found: " + "counts[" + id + "] = " + counts[id] + ", should be "
  31.                             + i);
  32.                     return;
  33.                 }
  34.                 // NOTE: no synchronization
  35.                 counts[id] = (byte) (i + 1);
  36.             }
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement