0

I have the following:


private int i;

public int getI() {
    return i;
}

public synchronized int getISync() {
    return i;
}

From a strict safety point of view (neglecting the fact that getISync implies locks), is getI immune to thread interference? I mean, is it safe? Does getISync offer something more, or is just the same thing in regard of safety? If there's a difference, please explain.

N.B. I know that on int fields (in this example), read and write operations are natively considered atomic.

artaxerxe
  • 6,281
  • 21
  • 68
  • 106
  • 1
    Did you mean to make `i` volatile? You mention volatility in your title, but ehn nowhere else... – Jon Skeet Apr 04 '15 at 10:01
  • 2
    Write atomicity is nowhere close to all you need to be thread-safe. You need to ensure *visibility* of that write, which is not implied by atomicity. – Marko Topolnik Apr 04 '15 at 10:05
  • @JonSkeet I think `int` is natively volatile. I mentioned it just for the point. Think to be ok (new to concurrency :( ). – artaxerxe Apr 04 '15 at 10:12
  • 1
    @artaxerxe: No, `int` writes are atomic, but not volatile. They're different concepts. – Jon Skeet Apr 04 '15 at 11:30

0 Answers0