Can synchronized blocks be faster than Atomics?

后端 未结 5 1813
天命终不由人
天命终不由人 2021-02-15 15:10

Suppose two following counter implementations:

class Counter {
  private final AtomicInteger atomic = new AtomicInteger(0);
  private int i = 0;

  public void i         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-02-15 15:42

    It's implementation dependent - so ultimately you'll need to benchmark on your particualar platform / JVM / configuration.

    Having said that, atomics should always be faster for the following reasons:

    • Atomics are designed so that the JVM can take advantage of atomic machine instructions, which are the fastest atomic operations that you can get for most platforms
    • synchronized makes use of relatively heavyweight locking schemes with monitor objects, which is designed to protect potentially large blocks of code. This form of locking in inherently more complicated than atomic operations so you would expect it to have higher runtime cost.

提交回复
热议问题