Connecting Tech Pros Worldwide Help | Site Map

Whats wrong with this loop code?

Newbie
 
Join Date: Aug 2009
Posts: 3
#1: Aug 21 '09
Sometimes it works, sometimes it doesn't but I can't find the bug:

Expand|Select|Wrap|Line Numbers
  1. package Loop.Test;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5.  
  6. public class TheLoopTest {
  7.  
  8.         private final ExecutorService executorService = Executors.newFixedThreadPool(100);
  9.         private static final int MAX = 1000;
  10.         private int zeroToTop = 0;
  11.  
  12.         TheLoopTest() throws InterruptedException {
  13.                 for (int i = 0; i < MAX; i++) {
  14.                         executorService.execute(new Runnable() {
  15.                                 public void run() {
  16.                                         incrementAllTheWay();
  17.                                 }
  18.                         });
  19.                 }
  20.                 executorService.shutdown();
  21.                 while (!executorService.isTerminated()) {
  22.                         Thread.sleep(500);
  23.                 }
  24.                 System.out.println(zeroTotop);
  25.         }
  26.  
  27.         private void incrementAllTheWay() {
  28.                 int obfusticatedIncremental = zeroToTop;
  29.                 obfusticatedIncremental = obfusticatedIncremental + 1;
  30.                 zeroToTop = obfusticatedIncremental;
  31.         }
  32.  
  33.         /**
  34.          * @param args
  35.          */
  36.         public static void main(String[] args) throws InterruptedException {
  37.                 new TheLoopTest();
  38.         }
  39.  
  40. }
  41.  
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Aug 21 '09

re: Whats wrong with this loop code?


Can you tells us what you think this thing is supposed to do and what it actually does? This is not a guessing forum.

kind regards,

Jos
Newbie
 
Join Date: Aug 2009
Posts: 3
#3: Aug 27 '09

re: Whats wrong with this loop code?


Still not working, any other suggestions?
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#4: Aug 27 '09

re: Whats wrong with this loop code?


Quote:

Originally Posted by wordone View Post

Still not working, any other suggestions?

Please answer my question (see my previous reply). If not I'm out of here; this is not a guessing forum.

kind regards,

Jos
Newbie
 
Join Date: Aug 2009
Posts: 3
#5: Sep 15 '09

re: Whats wrong with this loop code?


It's about a race condition and it should print out '1000' every time but it doesn't always. I tried to change Executors.newFixedThreadPool(100); to match the Thread.sleep(500); so the times are the same but that didn't seem to fix it.
Reply