fork download
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class VolatileTest {
  5. public static void main(final String[] args) throws InterruptedException {
  6. final long start = System.currentTimeMillis();
  7. final int max = 5000;
  8. final int maxThreads = 2;
  9. for (int i = 0; i < max; i++) {
  10. final List<Thread> threadList = new ArrayList<>();
  11. for (int j = 0; j < maxThreads; j++) {
  12. threadList.add(new Thread(new Runnable() {
  13. @Override
  14. public void run() {
  15. do_something();
  16. }
  17. }));
  18. }
  19. for (final Thread thread : threadList)
  20. thread.start();
  21. for (final Thread thread : threadList)
  22. thread.join();
  23. }
  24. final long end = System.currentTimeMillis();
  25. System.out.println((end - start) + " ms");
  26. // for 2 threads:
  27. // 16407 ms (w/o volatile counter)
  28. // 176203 ms
  29. // 1 thread
  30. // 10687 ms (w/o volatile counter)
  31. // 154345 ms
  32. // intel snb 3.3 ghz, 2x2 cores
  33. }
  34.  
  35. static int value = 1; // add volatile for volatile run
  36. static final int maxcount = 100_000_000;
  37.  
  38. public static int do_something() {
  39. int sum = 0;
  40. for (int i = 0; i < maxcount; i++) {
  41. sum += value;
  42. }
  43. return sum;
  44. }
  45. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty