Whats wrong with this loop code?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wordone
    New Member
    • Aug 2009
    • 9

    Whats wrong with this loop code?

    Sometimes it works, sometimes it doesn't but I can't find the bug:

    Code:
    package Loop.Test;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class TheLoopTest {
    
            private final ExecutorService executorService = Executors.newFixedThreadPool(100);
            private static final int MAX = 1000;
            private int zeroToTop = 0;
    
            TheLoopTest() throws InterruptedException {
                    for (int i = 0; i < MAX; i++) {
                            executorService.execute(new Runnable() {
                                    public void run() {
                                            incrementAllTheWay();
                                    }
                            });
                    }
                    executorService.shutdown();
                    while (!executorService.isTerminated()) {
                            Thread.sleep(500);
                    }
                    System.out.println(zeroTotop);
            }
    
            private void incrementAllTheWay() {
                    int obfusticatedIncremental = zeroToTop;
                    obfusticatedIncremental = obfusticatedIncremental + 1;
                    zeroToTop = obfusticatedIncremental;
            }
    
            /**
             * @param args
             */
            public static void main(String[] args) throws InterruptedException {
                    new TheLoopTest();
            }
    
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    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

    Comment

    • wordone
      New Member
      • Aug 2009
      • 9

      #3
      Still not working, any other suggestions?

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by wordone
        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

        Comment

        • wordone
          New Member
          • Aug 2009
          • 9

          #5
          It's about a race condition and it should print out '1000' every time but it doesn't always. I tried to change Executors.newFi xedThreadPool(1 00); to match the Thread.sleep(50 0); so the times are the same but that didn't seem to fix it.

          Comment

          Working...