0

Suppose there is a counter which is incremented by several threads. Are the following implementations equivalent?

Implementation 1 (Use volatile modifier only):

class Test1 {
  private volatile int counter;
  ...
  void increment() {
    counter ++;
  }
}

Implementation 2 (Volatile modifier is not used, instead the synchronized block is used):

class Test2 {
  private int counter;
  ...
  void increment() {
    synchronized(this) {
      counter ++;
    }
  }
}
Mega Noob
  • 11
  • 3
  • Those are not the same thing. Making field a `volatile` does not guarantees access synchronization like `synchronized` block do. – Antoniossss Jan 08 '21 at 09:36
  • No they are not the same. See https://stackoverflow.com/questions/3519664/difference-between-volatile-and-synchronized-in-java – M A Jan 08 '21 at 09:36
  • Have you tried to write some unit tests to dis/prove your thesis? The idea behind my question is that trying to test it might give you valuable skills of understanding how synchronized and volatile work, how to test such issue and possible get an answer to your question - which you can post as your finding eventually :) – Nikolas Charalambidis Jan 08 '21 at 09:37
  • 1
    Note that the question in the title and in the body are very different. – luk2302 Jan 08 '21 at 09:39

0 Answers0