0

The following problem is on a mock exam for the OCP Java SE 7 Programmer II Exam. The solution says the answer is 0, but my colleagues and I are not sure that the answer isn't between -5 and 5 (which is a choice) Could someone clarify this for us? Here is the code:

import java.util.concurrent.atomic.AtomicInteger;
class AtomicVariableTest {
        private static AtomicInteger counter = new AtomicInteger(0);
        static class Decrementer extends Thread {
                public void run() {
                        counter.decrementAndGet(); // #1
                }
         }
        static class Incrementer extends Thread {
                public void run() {
                        counter.incrementAndGet(); // #2
                }
         }
        public static void main(String []args) {
                for(int i = 0; i < 5; i++) {
                        new Incrementer().start();
                        new Decrementer().start();
                }
                System.out.println(counter);
         }
}

Thanks!

Shoikana
  • 595
  • 4
  • 8
  • 3
    It's between -5 and 5. Of the 10 threads you started, you don't know how many have actually done their work before you print the counter, because you didn't wait for them to finish. – Matt Timmermans Jun 11 '16 at 13:11
  • 1
    @SotiriosDelimanolis - i don't think you meant "undefined" (there are no thread unsafe actions here). i think you meant "non-deterministic" since (as @MattTimmermans) points out, you don't know which threads have completed – jtahlborn Jun 11 '16 at 14:15
  • 1
    @jtah Yeah, what you said. – Sotirios Delimanolis Jun 11 '16 at 14:29

1 Answers1

0

Running it multiple times with some logs shows that the order in which the threads are ran change the outcome. On multiple runs, I did get 0, but results experimentally varied from -1 to 2 on my machine. I would say that the only valid answer to this is : Between -5 and 5.

class AtomicVariableTest
{
    private static AtomicInteger counter = new AtomicInteger(0);

    static class Decrementer extends Thread
    {
        public void run()
        {
            counter.decrementAndGet(); // #1
            System.out.println("dec");
        }
    }

    static class Incrementer extends Thread
    {
        public void run()
        {
            counter.incrementAndGet(); // #2
            System.out.println("inc");
        }
    }

    public static void main(String[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            new Incrementer().start();
            new Decrementer().start();
        }
        System.out.println(counter);
    }
}

Output of this program is looking like this :

inc
dec
inc
dec
inc
dec
inc
dec
0
inc
dec

dec
-1
inc
dec
inc
dec
dec
dec
inc
inc
inc
Demogorii
  • 656
  • 5
  • 16