线程安全并发处理原理分析和控制

jvm主内存与工作内存

主内存主要包括本地方法区和堆。每个线程都有一个工作内存,工作内存中主要包括两个部分,一个是属于该线程私有的栈和对主存部分变量拷贝的寄存器(包括程序计数器PC和cup工作的高速缓存区)。  

1.所有的变量都存储在主内存中(虚拟机内存的一部分),对于所有线程都是共享的。

2.每条线程都有自己的工作内存,工作内存中保存的是主存中某些变量的拷贝,线程对变量的所有操作都必须在工作内存中进行,而不能直接读写主内存中的变量。
3.线程之间无法直接访问对方的工作内存中的变量,线程间变量的传递均需要通过主内存来完成。

JVM规范定义了线程对内存间交互操作:

Lock(锁定):作用于主内存中的变量,把一个变量标识为一条线程独占的状态。

Read(读取):作用于主内存中的变量,把一个变量的值从主内存传输到线程的工作内存中。

Load(加载):作用于工作内存中的变量,把read操作从主内存中得到的变量的值放入工作内存的变量副本中。

Use(使用):作用于工作内存中的变量,把工作内存中一个变量的值传递给执行引擎。

Assign(赋值):作用于工作内存中的变量,把一个从执行引擎接收到的值赋值给工作内存中的变量。

Store(存储):作用于工作内存中的变量,把工作内存中的一个变量的值传送到主内存中。

Write(写入):作用于主内存中的变量,把store操作从工作内存中得到的变量的值放入主内存的变量中。

Unlock(解锁):作用于主内存中的变量,把一个处于锁定状态的变量释放出来,之后可被其它线程锁定。

多线程影响:

使用actomic CAS来控制并发:

jdk1.8AtomicInteger

package java.util.concurrent.atomic;

找到getandaddint的实现:

var5通过获取本地中的变量(其实应该取的是主存的值),然后比较当前的var2的值与本地变量var5是否相等,如果不相等则重复判断,直到相等才执行增加操作。这样就保证数据的一致性。这个也叫做CMS。其中var5为主内存数据

修改代码:

package com.mmall.concurrency;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class concurrency {

    // 请求次数
    public static  int clientTotal = 5000;

    //  请求人数
    public static  int threadTotal = 200;
    // 该count存储的是工作内存
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i ++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(count);

    }

    private static void add() {
        count.incrementAndGet();
    }
}

此方法将工作内存和主内存的值保持一致。

使用AtomicLong原理一样:

public static AtomicLong count = new AtomicLong(0);

在jdk1.8中新增LongAdder

 public static LongAdder count = new LongAdder();

private static void add() {
        count.increment();
    }

为什么有了AtomicLong还要有LongAdder?

AutomaticLong的底层是通过CAS(compareAndSwap)来实现线程的同步,是在一个死循环内不断的尝试修改目标的值,直到修改成功。如果在竞争不激烈的情况下,它修改成功的概率很高,否则的话修改失败的概率就会很高, 在大量修改失败的时候这些原子操作就会多次循环尝试, 因此性能就会受到影响。对于普通类型的long和dubble变量JVM允许将64位的读或者写操作拆分成2个32位的读或者写操作,LongAdder的内部实现思想是: 将热点数据分离,将AutomaticLong的内部核心数据value分割成一个数组,每个线程访问时,通过Hash等算法映射到其中一个数字进行计数,最终的计数结果为这个数组的求和累加,其中热点数据value他会被分割成多个单元的cell,每个cell独立维护内部的值,当前对象的实际值由所有的cell累计合成,这样热点就进行了有效的分离,提高了并行度。即LongAdder是在AtomicLong的基础上将单点的更新压力分散到各个节点上。在地并发的时候通过对base的值直接更新,可以很好地保证和AutomaticLong性能基本一致,而在高并发的时候则通过分散提高了性能。LongAdder缺点:在统计的时候如果有并发更新,可能会导致统计的数据有些误差。在实际处理高并发中,我们根据实际业务场景优先考虑使用LongAdder而不是继续使用AtomicLong,当然在线程竞争很低的情况下AutomaticLong才是最佳选择(序列号生成等要求准确且全局唯一)。

AtomicStampReference解决CAS的ABA问题:

package com.mmall.concurrency.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 作者: lin
 * 描述:
 * 日期: 2018/9/29 16:58
 */
public class concurrency4 {

    public static AtomicBoolean  ishappend = new AtomicBoolean(false);


    // 请求次数
    public static  int clientTotal = 5000;

    //  请求人数
    public static  int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i ++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(ishappend.get());
    }
    private static void test(){
        if (ishappend.compareAndSet(false,true)){
            System.out.println("改变为true");
        }

    }

}

使某段代码只执行一次。比较常用。

synchronized:依赖jvm,不可中断

Lock:依赖特殊的cpu指令

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值