My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Copyright (c) 2011. Peter Lawrey
*
* "THE BEER-WARE LICENSE" (Revision 128)
* As long as you retain this notice you can do whatever you want with this stuff.
* If we meet some day, and you think this stuff is worth it, you can buy me a beer in return
* There is no warranty.
*/

package com.google.code.java.core.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class IncrementNotThreadSafeMain {
public static void main(String... args) throws InterruptedException {
for (int nThreads = 1; nThreads <= 64; nThreads *= 2)
doThreadSafeTest(nThreads);
}

static class VolatileInt {
volatile int num = 0;
}

private static void doThreadSafeTest(final int nThreads) throws InterruptedException {
final int count = 100 * 1000 * 1000;

ExecutorService es = Executors.newFixedThreadPool(nThreads);
final VolatileInt vi = new VolatileInt();
// final AtomicInteger num = new AtomicInteger();
for (int i = 0; i < nThreads; i++)
es.submit(new Runnable() {
public void run() {
for (int j = 0; j < count; j += nThreads)
vi.num++;
// num.incrementAndGet();
}
});
es.shutdown();
es.awaitTermination(1, TimeUnit.MINUTES);
assert es.isTerminated();
System.out.printf("With %,d threads should total %,d but was %,d%n", nThreads, count, vi.num /*num.longValue()*/);
}

}

Change log

r58 by peter.lawrey on Aug 30, 2011   Diff
Beerware licensing.
Go to: 
Project members, sign in to write a code review

Older revisions

r51 by peter.lawrey on Aug 13, 2011   Diff
Test to show thread safety.
All revisions of this file

File info

Size: 1485 bytes, 46 lines
Powered by Google Project Hosting