Can synchronized blocks be faster than Atomics?

后端 未结 5 1808
天命终不由人
天命终不由人 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:53

    As others have said this is implementation dependent . But keep in mind that if your program invariants involve more than one variable , then you have to use synchronization to update them together . You can't do atomic operation on two related variables together just because they are of Atomic type. In that case your only friend is synchronized .

提交回复
热议问题