synchronized

synchronized


前提

  • java -version 1.8.0

概述

  • 场景:解决并发问题
  • 特点:
    • 可锁重入锁,即在使用 synchronized 时,当一个线程得到了一个对象的锁后,再次请求此对象时可以再次得到该对象的锁;
    • 重量级锁
  • 作用:
    • 确保线程互斥的访问同步代码
    • 保证共享变量的修改能够及时可见
    • 有效解决重排序问题
  • 用法:
修饰内容锁类型示例
修饰代码块任意对象锁示例四
修饰普通方法this锁示例五
修饰静态方法类锁示例六
  • 非静态方法:给对象加锁(可以理解为给这个对象的内存上锁,注意 只是这块内存,其他同类对象都会有各自的内存锁),这时候在其他一个以上线程中执行该对象的这个同步方法(注意:是该对象)就会产生互斥
  • 静态方法: 相当于在类上加锁(*.class 位于代码区,静态方法位于静态区域,这个类产生的对象公用这个静态方法,所以这块内存,N个对象来竞争), 这时候,只要是这个类产生的对象,在调用这个静态方法时都会产生互斥
  • 修饰代码块
    • 若锁对象为 Object obj = new Object() 任意对象,不同线程间串行访问同步代码块
    • 若所对象为 this , 同一个对象的不同方法间串行访问同步代码块
    • 若锁对象为 类.class ,同一个类声明的所有对象运行的方法串行访问代码块
  • static 修饰的共享变量,需要使用类锁
  • 对一个全局对象或者类加锁时,对该类的所有对象都起作用

  • synchronized关键字是不能继承的,也就是说,基类的方法synchronized f(){} 在继承类中并不自动是synchronized f(){},而是变成了f(){}。继承类需要你显式的指定它的某个方法为synchronized方法

  • synchronized锁住的是括号里的对象,而不是代码。对于非static的synchronized方法,锁的就是对象本身也就是this
  • synchronized锁的内容应尽量短小,原因在于加锁部分需线程进行判断获取锁,获取不到则需等待,影响整体运行的效率;锁应只加在需要并发控制的地方

实现原理

  • 示例一
/**
 *  修饰代码块(锁类型:this锁)
 */
public class SynchronizedDemo1 {
    public void method(){
        synchronized (this) {
            System.out.println("hello world");
        }
    }
}
  • 反编译

synchronized修饰代码块

  • monitorenter

Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
• If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
• If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
• If another thread already owns the monitor associated with objectref, the thread blocks until the monitor’s entry count is zero, then tries again to gain ownership.

  • 每个对象有一个监视器锁(monitor)。当monitor被占用时就会处于锁定状态,线程执行monitorenter指令时尝试获取monitor的所有权,过程如下:
    • 如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者。
    • 如果线程已经占有该monitor,只是重新进入,则进入monitor的进入数加1.
    • 如果其他线程已经占用了monitor,则该线程进入阻塞状态,直到monitor的进入数为0,再重新尝试获取monitor的所有权。
  • 总结

    • Synchronize 可重入锁,即如果当前线程以获得锁对象,可再次获取该锁对象
    • 即:该锁对象的监视器锁 monitor 具有可重入性,每进入一次,进入次数+1
    • 从 synchronized 使用的语法上,如果修饰代码块,synchronize (object ) {} object 即为锁对象
    • 如果修饰方法,普通方法可认为是 this 锁,即当前对象锁;静态方法可认为是 类锁
  • monitorentry流程如图:
    monitorentry流程

  • monitorexit

The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.

  • 执行monitorexit的线程必须是objectref所对应的monitor的所有者。
  • 指令执行时,monitor的进入数减1,如果减1后进入数为0,那线程退出monitor,不再是这个monitor的所有者。其他被这个monitor阻塞的线程可以尝试去获取这个 monitor 的所有权
  • 总结:通过这两段描述,我们应该能很清楚的看出Synchronized的实现原理,Synchronized的语义底层是通过一个monitor的对象来完成,其实wait/notify等方法也依赖于monitor对象,这就是为什么只有在同步的块或者方法中才能调用wait/notify等方法,否则会抛出java.lang.IllegalMonitorStateException的异常的原因

  • 示例二
/**
 *  修饰普通方法(锁类型:对象锁) 
 */
public class SynchronizedDemo2 {

    public synchronized void methodA(){
        System.out.println("hello world");
    }

    public synchronized void methodB(){
        System.out.println("hello world");
    }
}

synchronized修饰普通方法

  • 示例三

/**
 * 修饰静态方法(锁类型:类锁) 
 */
public class SynchronizedDemo3 {

    public static synchronized void methodA(){

    }

    public static synchronized void methodB(){

    }
}

synchronized修饰静态方法

  • 从反编译的结果来看,方法的同步并没有通过指令monitorenter和monitorexit来完成(理论上其实也可以通过这两条指令来实现),不过相对于普通方法,其常量池中多了ACC_SYNCHRONIZED标示符。JVM就是根据该标示符来实现方法的同步的:当方法调用时,调用指令将会检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置,如果设置了,执行线程将先获取monitor,获取成功之后才能执行方法体,方法执行完后再释放monitor。在方法执行期间,其他任何线程都无法再获得同一个monitor对象。 其实本质上没有区别,只是方法的同步是一种隐式的方式来实现,无需通过字节码来完成

  • 反编译操作:

    • javap 是JDK自带的反汇编器,可以查看java编译器生成的字节码。常用参数如下:
      • -c:输出类中各方法的未解析的代码,即构成 Java 字节码的指令
      • -verbose:输出堆栈大小、各方法的 locals 及 args 数,以及class文件的编译版本
    • 使用:windows+R ,输入 cmd ,打开运行窗口,cd 到 class 文件存放的路径,执行如下命令
    • 命令:javap -verbose xxx.class (文件的路径)

  • 示例四
/**
 *  修饰代码块(锁类型:任意对象锁)
 */
/**
 *  未加 synchronized 前的输出结果
    t1-method start
    t2-method start
    t1-method end
    t2-method end
 *
 *  从输出结果上看,method 方法未按照顺序执行
 *  即,t1 未执行完 method 方法,t2 已开始执行
 *  所以,输出结果中包含交叉打印的内容
 */
/**
 *  添加 synchronized 后的输出结果
    t2-method start
    t2-method end
    t1-method start
    t1-method end
 *  
 *  从输出结果上看,method 方法按照顺序执行
 *  对需要线程互斥访问的代码块添加  synchronized 锁
 */
public class SynchronizedDemo1 {

    private Object object = new Object();

    public void method(){

        synchronized (object) {

            System.out.println(Thread.currentThread().getName()+"-method start");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"-method end");
        }
    }

    public static void main(String[] args) {

        final SynchronizedDemo1 test = new SynchronizedDemo1();
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                test.method();
            }
        },"t1");

        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                test.method();
            }
        },"t2");

        thread1.start();
        thread2.start();
    }
}
  • 示例
/**
 *  修饰普通方法(锁类型:对象锁) 
 */
/**
 *  未加 synchronized 前的输出结果
    t1-methodA start
    t2-methodB start
    t1-methodA end
    t2-methodB end
 *
 */
/**
 *  添加 synchronized 后的输出结果
    t1-methodA start
    t1-methodA end
    t2-methodB start
    t2-methodB end
 *  
 */
public class SynchronizedDemo2 {

    public synchronized void methodA(){
        System.out.println(Thread.currentThread().getName()+"-"+"methodA start");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-"+"methodA end");
    }

    public synchronized void methodB(){
        System.out.println(Thread.currentThread().getName()+"-"+"methodB start");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-"+"methodB end");
    }

    public static void main(String[] args) {
        final SynchronizedDemo2 demo = new SynchronizedDemo2();
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                demo.methodA();
            }
        },"t1");

        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                demo.methodB();
            }
        },"t2");

        thread1.start();
        thread2.start();
    }

}
  • 示例
/**
 * 修饰静态方法(锁类型:类锁) 
 */
/**
 *  未加 synchronized 前的输出结果
    t1-methodA start
    t2-methodB start
    t1-methodA end
    t2-methodB end
 *
 */
/**
 *  添加 synchronized 后的输出结果
    t1-methodA start
    t1-methodA end
    t2-methodB start
    t2-methodB end
 *  
 */
public class SynchronizedDemo3 {

    public static synchronized void methodA(){
        System.out.println(Thread.currentThread().getName()+"-"+"methodA start");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-"+"methodA end");
    }

    public static synchronized void methodB(){
        System.out.println(Thread.currentThread().getName()+"-"+"methodB start");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-"+"methodB end");
    }

    public static void main(String[] args) {
        final SynchronizedDemo3 demo1 = new SynchronizedDemo3();
        final SynchronizedDemo3 demo2 = new SynchronizedDemo3();
        Thread thread1 = new Thread(new Runnable() {

            @SuppressWarnings("static-access")
            @Override
            public void run() {
                demo1.methodA();
            }
        },"t1");
        Thread thread2 = new Thread(new Runnable() {

            @SuppressWarnings("static-access")
            @Override
            public void run() {
                demo2.methodB();
            }
        },"t2");

        thread1.start();
        thread2.start();

    }
}

String 作为synchronized 的锁对象

  • synchronized 修饰代码块时,所使用的锁对象,对于不同的线程来说必须是同一个,因为是同一个所以才会有资源竞争;争抢到锁的线程才可以执行,其他的线程则阻塞等待
  • String 对象不可变,但变量引用可变更,所以可以使用String 作为锁对象;String 常量池,同一个字符串内容,通过 String 类中 intern 方法返回的都是同一个地址
  • 注意:使用字符串作为锁对象,考虑到业务场景,字符串具有一定的业务含义;此时,字符串是通过+拼接或是通过StringBuilder 、StringBuffer 拼接,调用 toString() 获取字符串;但 StringBuilder 中的 toStirng() 方法,返回的是 new String() 即每次调用都会返回一个新生成的字符串;而 synchronized 起作用的前提是多线程对同一个锁对象的竞争,才能保证同步代码块的串行访问;
  • 解决:使用 String 字符串作为锁,要调用 String 中的 intern 方法,通过String的常量池获取对象的引用,且同一个字符串的引用一定是相同的
  • 在Java中是有常量池缓存的功能的,就是说如果先声明了一个String str1 = “a”; 再声明一个一样的字符串的时候,取值是从原地址去取的,也就是说是同一个对象。这也就导致了在锁字符串对象的时候,可以会取得意料之外的结果(字符串一样会取得相同锁);每次传入锁参数时,均声明新的字符串对象可避免此问题
  • 慎用String作为synchronized的锁对象
  • String.intern放进的String Pool是一个固定大小的Hashtable,默认值是1009,如果放进String Pool的String非常多,就会造成Hash冲突严重,从而导致链表会很长,而链表长了后直接会造成的影响就是当调用String.intern时性能会大幅下降(因为要一个一个找);
  • String.intern()会在heap里产生空间,而且还是老年代,如果对象一多就会导致Full GC时间超长
  • 解决办法:引用 google-guava 包
synchronized (("" + userId).intern()) {
            // TODO:something
   }
// 改为
Interner<String> pool = Interners.newWeakInterner();

synchronized ( pool.intern("BizCode"+userId)){

//TODO:something

}

参考资料

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值