Can synchronized blocks be faster than Atomics?

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

    Or some situations exists when this rule is broken (e.g. SMP/Single CPU machine, different CPU ISA, OS'es etc.)?

    I don't know of any. (And I stand ready to be corrected ... if someone knows of a concrete counter-example.)

    However (and this is my main point) there is no theoretical reason why you couldn't have a hardware architecture or a poorly implemented JVM in which synchronized is the same speed or faster than the atomic types. (The relative speed of these two forms of synchronization is an implementation issue, and as such can only be quantified for existing implementations.)

    And of course, this doesn't mean you should never use synchronized. The synchronized construct has many use-cases that the atomic classes don't address.

提交回复
热议问题