0

I'm aware that including the word synchronized to the getNext() method signature would make the method completely thread safe. But what if in the body of the method I surround only the portion where the actual incrementing is being done with a synchronized block? Will this still be a completely thread safe incrementer? What's the difference?

public class NextNumberGenerator {

    private int number = 0;

    public int getNext() {
        synchronized (this) {
            number = number + 1;
        }

        return number;
    }
}
user836087
  • 2,271
  • 8
  • 23
  • 33
  • 4
    Well, the *incrementing* will be safe, but the `return number;` won't be. If two threads call `getNext`, both of them could return `2`. – user2357112 Jul 27 '17 at 22:34
  • The standard way to implement a generator like this is to use the [`AtomicInteger`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html) class. – Mick Mnemonic Jul 27 '17 at 22:42
  • But I can't see through to that. The updating will be a locked step. So what ever thread reads the number, it should get the updated number no? So then where could it be possible for repeats? Could you break down a bit how 2 threads may cause a problem here? I'm unable to see that deeply. – user836087 Jul 27 '17 at 22:43
  • _should get the updated number_ The updated number from the current thread or from another thread? You're reading the `number` field outside the `synchronized` block. – Sotirios Delimanolis Jul 27 '17 at 22:44
  • 2
    The last line reads the number field outside the synchronized block. Suppose the first thread updates the number from 0 to 1, exits the synchronized block, and then (before the first thread reads the number field) another thread calls `getNext()` and changes the number from 1 to 2. When the first thread reads the number, it will be 2 instead of 1. – tom Jul 27 '17 at 22:52
  • well wouldn't it be the same instance of NextNumberGenerator who's number field has been updated in the atomic operation? So another thread will read that number belonging to the instance of NextNumberGenerator no? – user836087 Jul 27 '17 at 22:54
  • 1
    Exactly. And that's where the problem is: two threads calling getNext() can read and return the same value. So, imagine you use getNext() to generate a unique invoice number, two threads might generate two invoices with the same number. You don't want that, do you? – JB Nizet Jul 27 '17 at 23:03
  • thank u i finally got it – user836087 Jul 27 '17 at 23:05

0 Answers0