Giter VIP home page Giter VIP logo

Comments (1)

lov3blacksilk avatar lov3blacksilk commented on June 11, 2024 9

一. 我们经常会使用i++操作,大家都知道这个并不是线程安全的,这时通常会使用synchroized关键字来处理并发操作,在并发量不大的情况使用synchroized性能并不是特别高。在jdk1.6以前synchroized是重量级锁,无论有没有资源竞争都会对变量加锁,在jdk1.6之后引入了偏向锁和轻量级锁,效率才有了很大的提升。atomic类使用了cas的**,只有真正资源竞争的时候才会有资源消耗,而且atomic是通过底层硬件指令集实现的,所以并发量不大的情况下性能更高。
二. 主要原理就是CAS(比较和交换), 涉及到三个值(V, O, N), V是内存中真正的值,O是加载到线程中的预期值,N是计算后的目标结果值,当计算出目标结果值时比较V和O是否相等,不相等代表V被其他线程改写过,那么将V重新赋值给O,然后重新计算目标值,再次重复上述步骤,这个称为自旋操作。
缺点:

  1. 存在ABA问题,因为每次都比较O和V的值,如果在比较之前V被多次改写过,最终的值还是之前的V,那么仅仅比较最终的V和O是无法知道这种情况的。
  2. 只能针对一个共享变量进行原子操作。
  3. 可以看到当V和O不等的时候就需要自旋操作,当并发数量很多,资源竞争激烈时,进行自旋操作等待的时间会很长,性能会大幅度降低,这时候使用其他锁会比较合适

from android-daily-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.