詳解Synchronized鎖的各種用法及注意事項
本文轉載自微信公眾號「源碼筆記」,作者 源碼筆記 。轉載本文請聯系源碼筆記公眾號。
1 前言
本文主要通過簡單的demo來闡述synchronized鎖的各種用法以及使用synchronized鎖的相關注意事項,記錄下來同時也方便自己記憶。
synchronized鎖是jvm內置的鎖,不同于ReentrantLock鎖。synchronized關鍵字可以修飾方法,也可以修飾代碼塊。synchronized關鍵字修飾方法時可以修飾靜態方法,也可以修飾非靜態方法;同樣,synchronized關鍵字修飾代碼塊時可以修飾對象,也可以修飾類。當然,synchronized修飾靜態方法/類和非靜態方法/對象時的作用范圍是不同的。下面通過各種demo來詳解synchronized的各種用法及注意事項。
2 synchronized類鎖
這里所說的synchronized類鎖的作用范圍是類級別的,不會因為同一個類的不同對象執行而失效。
2.1 synchronized修飾同一個類的兩個靜態方法時互斥
- public class SynchronizeAndClassLock {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- // new了一個ClassLock對象
- new ClassLock().test1();
- }).start();
- new Thread(() -> {
- // new了另一個ClassLock對象
- new ClassLock().test2();
- }).start();
- }
- }
- class ClassLock {
- public synchronized static void test1(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- // 【注意】public static void test2(){ 不會互斥,因為此時test2沒有使用類鎖。
- public synchronized static void test2(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
運行結果:
【結論】兩個線程分別同時執行同一個類產生的不同對象的兩個不同 synchronized static方法,類鎖生效,雖然是不同對象,因為兩個線程使用的是同一個類鎖。反過來,假如test2方法沒有synchronized修飾的話,只有test1方法有被synchronized修飾,此時兩個方法也不會互斥,一個有鎖,一個沒有鎖,自然不會互斥。
2.2 synchronized分別修飾同一個類的靜態方法和當前類時互斥
- public class SynchronizeAndClassLock2 {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- // new了一個ClassLock2對象
- new ClassLock2().test1();
- // ClassLock2.test1();
- }).start();
- new Thread(() -> {
- // new了另一個ClassLock2對象
- new ClassLock2().test2();
- // ClassLock2.test2();
- }).start();
- }
- }
- class ClassLock2 {
- public synchronized static void test1(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- public static void test2(){
- // 【注意】synchronized (SynchronizeAndClassLock2.class)不會互斥
- synchronized (ClassLock2.class) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- }
運行結果:
【結論】兩個線程同時分別執行一個被synchronized修飾static方法,一個有synchnized(該類)代碼塊的static方法,鎖生效,雖然是不同對象,因為兩個線程使用的同一個類鎖。反過來,如果是修飾的不同類,因為類鎖不同,肯定不會互斥,比如將test2方法的synchronized (ClassLock2.class)這句代碼改成synchronized (SynchronizeAndClassLock2.class),此時不會互斥。
2.3 synchronized分別修飾同一個靜態對象時互斥
- public class SynchronizeAndClassLock10 {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- new RunObject1().test1();
- }).start();
- new Thread(() -> {
- new RunObject2().test2();
- }).start();
- }
- }
- class RunObject1 {
- public static void test1(){
- // 【1】synchronized (StaticLock2.staticLock1) {
- synchronized (StaticLock2.staticLock) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- }
- class RunObject2 {
- public static void test2() {
- // 【2】synchronized (StaticLock2.staticLock2) {
- synchronized (StaticLock2.staticLock) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- }
- class StaticLock2 {
- public static Object staticLock = new Object();
- }
運行結果:
【結論】synchronized分別修飾同一個類的靜態對象時互斥,反過來,如果是修飾不同的靜態對象,肯定不會互斥,比如將上面代碼中標【1】和【2】的synchronized代碼結合使用。
3 synchronized對象鎖
這里說的synchronized對象鎖的作用范圍是對象級別的即僅僅作用于同一個對象,如果是同一個類的兩個不同的對象是不會互斥的,即沒有效果的。
3.1 synchronized修飾同一個類對象的兩個非靜態方法時互斥
- public class SynchronizeAndObjectLock2 {
- public static void main(String[] args) throws Exception {
- // 【注意】當且僅當是同一個SynchronizeAndObjectLock2對象
- SynchronizeAndObjectLock2 synchronizeAndObjectLock2 = new SynchronizeAndObjectLock2();
- new Thread(() -> {
- synchronizeAndObjectLock2.test1();
- }).start();
- new Thread(() -> {
- synchronizeAndObjectLock2.test2();
- }).start();
- }
- public synchronized void test1(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- public synchronized void test2(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
運行結果:
【結論】兩個線程同時執行被synchronized修飾的相同對象的不同(相同)方法,鎖生效,因為兩個線程使用的是相同的對象鎖
3.2 synchronized分別修飾同一個類對象的非靜態方法和當前對象時互斥
- public class SynchronizeAndObjectLock3 {
- public static void main(String[] args) throws Exception {
- // 【注意】當且僅當是同一個SynchronizeAndObjectLock3對象
- SynchronizeAndObjectLock3 synchronizeAndObjectLock3 = new SynchronizeAndObjectLock3();
- new Thread(() -> {
- synchronizeAndObjectLock3.test1();
- }).start();
- new Thread(() -> {
- synchronizeAndObjectLock3.test2();
- }).start();
- }
- public void test1(){
- synchronized(this) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- public synchronized void test2(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
運行結果:
【結論】snchronized修飾非靜態方法與synchronized(this)互斥,可見,snchronized修飾非靜態方法實質鎖的是當前對象。
3.3 synchronized修飾不同對象的兩個非靜態方法時不會互斥
- public class SynchronizeAndObjectLock {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- // 這里new 了一個SynchronizeAndObjectLock對象
- new SynchronizeAndObjectLock().test1();
- }).start();
- new Thread(() -> {
- // 這里new 了另一個SynchronizeAndObjectLock對象
- new SynchronizeAndObjectLock().test2();
- }).start();
- }
- public synchronized void test1(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- public synchronized void test2(){
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
運行結果:
【結論】兩個線程同時執行被synchronized修飾的不同對象的不同(相同)方法,鎖未生效,因為兩個線程使用的是不同的對象鎖。
3.4 synchronized代碼塊修飾同一個對象時互斥
- public class SynchronizeAndObjectLock5 {
- private Object objectLock = new Object();
- public static void main(String[] args) throws Exception {
- SynchronizeAndObjectLock5 synchronizeAndObjectLock5 = new SynchronizeAndObjectLock5();
- new Thread(() -> {
- synchronizeAndObjectLock5.test1();
- }).start();
- new Thread(() -> {
- synchronizeAndObjectLock5.test2();
- }).start();
- }
- public void test1(){
- synchronized(objectLock) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- public void test2(){
- synchronized(objectLock) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- }
運行結果:
【結論】synchronized代碼塊修飾同一個對象時互斥,若synchronized代碼塊修飾的是不同對象,那么不會互斥。
4 synchronized修飾當前類和當前對象時不會互斥
- public class ClassAndObjectLock {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- ClassAndObjectLock.test1();
- }).start();
- new Thread(() -> {
- new ClassAndObjectLock().test2();
- }).start();
- }
- public static void test1(){
- synchronized (ClassAndObjectLock.class) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- public void test2(){
- synchronized (this) {
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (Exception e) {}
- System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");
- }
- }
- }
運行結果:
【結論】可見,類鎖和對象鎖是相互獨立的,互不相斥。
5 synchronized鎖注意事項
5.1 synchronized鎖不能被中斷
為了模擬synchronized鎖不可中斷,下面先讓兩個線程進入死鎖,然后再用main線程去中斷其中一個線程,看被中斷的線程能否釋放鎖并被喚醒。
- public class DeadLockCannotInterruptDemo {
- private static Object lock1 = new Object();
- private static Object lock2 = new Object();
- public static void main(String[] args) throws Exception {
- Thread threadA = new Thread(new Runnable() {
- @Override
- public void run() {
- synchronized (lock1) {
- System.out.println(Thread.currentThread().getName() + " get lock1");
- try {
- Thread.sleep(10);
- synchronized (lock2) {
- System.out.println(Thread.currentThread().getName() + " get lock2");
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- });
- Thread threadB = new Thread(new Runnable() {
- @Override
- public void run() {
- synchronized (lock2) {
- System.out.println(Thread.currentThread().getName() + " get lock2");
- try {
- Thread.sleep(10);
- synchronized (lock1) {
- System.out.println(Thread.currentThread().getName() + " get lock1");
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- });
- threadA.start();
- threadB.start();
- TimeUnit.SECONDS.sleep(3);
- System.out.println("main thread begin to interrupt " + threadA.getName() + " and " + threadA.getName() + " will release lock1...");
- threadA.interrupt();
- }
- }
運行結果:
【結論】如上圖,main線程中斷Thread-0后,Thread-0并不會釋放鎖并醒過來。同樣的,ReentrantLock的tryLock或lockInterruptibly是可以被中斷的。
5.2 synchronized鎖可重入
5.2.1 不同方法,synchronized是可重入的
- public class SynchronizeAndReentrant {
- public static void main(String[] args) throws Exception {
- SynchronizeAndReentrant synchronizeAndReentrant = new SynchronizeAndReentrant();
- synchronizeAndReentrant.test1();
- }
- public synchronized void test1(){
- System.out.println(" test1 method is called...");
- test2();
- }
- public synchronized void test2(){
- System.out.println(" test2 method is called...");
- }
- }
運行結果:
5.2.2 相同方法,synchronized是可重入的
- public class SynchronizeAndReentrant2 {
- int i = 1;
- public static void main(String[] args) throws Exception {
- SynchronizeAndReentrant2 synchronizeAndReentrant = new SynchronizeAndReentrant2();
- synchronizeAndReentrant.test1();
- }
- public synchronized void test1(){
- System.out.println(" test1 method is called " + i++ + "st time..." );
- while(i < 5) {
- test1();
- }
- }
- }
運行結果:
5.3 synchronized鎖不帶超時功能
synchronized鎖不帶超時功能,而ReentrantLock的tryLock是具備帶超時功能的,在指定時間沒獲取到鎖,該線程會蘇醒,有助于預防死鎖的產生。
5.4 喚醒/等待需要synchronized鎖
- public class NotifyNeedSynchronized {
- public static Object lock = new Object();
- public static void main(String[] args) throws Exception{
- // 拋出IllegalMonitorStateException
- //lock.notify();
- lock.wait();
- }
- }
運行結果:
【結論】使用Object的notify和wait等方法時,必須要使用synchronized鎖,否則會拋出IllegalMonitorStateException。
5.5 使用synchronized鎖時盡量縮小范圍以保證性能
使用synchronized鎖時,為了盡可能提高性能,我們應該盡量縮小鎖的范圍。能不鎖方法就不鎖方法,推薦盡量使用synchronized代碼塊來降低鎖的范圍。以下面的一段netty源碼為例:
- // ServerBootstrap.java
- public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value) {
- if (childOption == null) {
- throw new NullPointerException("childOption");
- }
- if (value == null) {
- synchronized (childOptions) {
- childOptions.remove(childOption);
- }
- } else {
- synchronized (childOptions) {
- childOptions.put(childOption, value);
- }
- }
- return this;
- }
可見,找到并發訪問代碼的臨界區,并不用synchronized鎖全部代碼,盡量避免使用synchronized來修飾方法。
6 總結
本文對synchronized的各種用法及注意事項通過demo簡單梳理了下,后面有時間會探討下synchronized的原理。