好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java编程读写锁详解

readwritelock也是一个接口,提供了readlock和writelock两种锁的操作机制,一个资源可以被多个线程同时读,或者被一个线程写,但是不能同时存在读和写线程。

基本规则: 读读不互斥 读写互斥 写写互斥

问题: 既然读读不互斥,为何还要加读锁

答: 如果只是读,是不需要加锁的,加锁本身就有性能上的损耗

如果读可以不是最新数据,也不需要加锁

如果读必须是最新数据,必须加 读写锁

读写锁相较于互斥锁的优点仅仅是允许读读的并发,除此之外并无其他。

结论: 读写锁能够保证读取数据的 严格实时性,如果不需要这种 严格实时性,那么不需要加读写锁。

简单实现:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

package readandwrite;

 

import java.util.random;

import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

import java.util.concurrent.locks.reentrantreadwritelock;

 

public class mytest {

  private static reentrantreadwritelock rwl= new reentrantreadwritelock();

  private static double data= 0 ;

  static class readclass implements runnable{

   @override

   public void run() {

    rwl.readlock().lock();

    system.out.println( "读数据:" +data);

    rwl.readlock().unlock();

   }

  }

 

  static class writeclass implements runnable{

   private double i;

  

   public writeclass( double i) {

    this .i = i;

   }

 

   @override

   public void run() {

    rwl.writelock().lock();

    data=i;

    system.out.println( "写数据: " +data);

    rwl.writelock().unlock();

   }

  

  }

  

  public static void main(string[] args) throws interruptedexception {

   executorservice pool=executors.newcachedthreadpool();

   for ( int i= 0 ;i< 10 ;i++){

    pool.submit( new readclass());

    pool.submit( new writeclass(( double ) new random().nextdouble()));

    pool.submit( new writeclass(( double ) new random().nextdouble()));

    thread.sleep( 1000 );

   }

   

   pool.shutdown();

  }

 

 

}

之前我们提到的锁都是排它锁(同一时刻只允许一个线程进行访问),而读写锁维护了一对锁,一个读锁,一个写锁。读写锁在同一时刻允许多个线程进行读操作,但是写线程访问过程中,所有的读线程和其他写线程均被阻塞。如此,并发性有了很大的提升。这样,在某些读远远大于写的场景中,读写锁能够提供比排它锁更好的并发量和吞吐量。

一个关于读写锁的demo:

分析:设计一个模拟队列,拥有一个data成员变量用于存储数据和存取两种操作。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

import java.util.random;

import java.util.concurrent.locks.readwritelock;

import java.util.concurrent.locks.reentrantreadwritelock;

 

public class readwritelockdemo

{

 

   public static void main(string[] args)

   {

     defqueue queue = new defqueue();

     for ( int i = 1 ; i < 10 ; i++)

     {

       //启动线程进行读操作

       new thread( new runnable()

       {

         @override

         public void run()

         {

           while ( true )

           {

             queue.get();

           }

         }

 

       }).start();

 

       //启动线程进行写操作

       new thread( new runnable()

       {

         @override

         public void run()

         {

           while ( true )

           {

             queue.put( new random().nextint( 10000 ));

           }

         }

       }).start();

     }

   }

 

}

 

class defqueue

{

   private int data;

   readwritelock rwlock = new reentrantreadwritelock();

 

   public void get()

   {

     rwlock.readlock().lock(); //加读锁

     try

     {

       system.out.println(thread.currentthread().getname() + "be ready to get data" );

       thread.sleep(( long ) (math.random() * 1000 ));

 

       system.out.println(thread.currentthread().getname() + "get the data:  " + data);

 

     } catch (interruptedexception e)

     {

       e.printstacktrace();

     } finally

     {

       rwlock.readlock().unlock(); //释放读锁

     }

   }

 

   public void put( int data)

   {

     rwlock.writelock().lock(); //加写锁

 

     try

     {

       system.out.println(thread.currentthread().getname() + " be ready to write data" );

 

       thread.sleep(( long ) (math.random() * 1000 ));

 

       this .data = data;

 

       system.out.println(thread.currentthread().getname() + " has wrote the data: " +data);

     } catch (interruptedexception e)

     {

       e.printstacktrace();

     } finally

     {

       rwlock.writelock().unlock(); //释放写锁

     }

 

   }

}

程序部分运行结果:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

thread-0be ready to get data

thread-0get the data:  0

thread- 1 be ready to write data

thread- 1 has wrote the data: 1156

thread-2be ready to get data

thread-2get the data:  1156

thread- 3 be ready to write data

thread- 3 has wrote the data: 9784

thread- 3 be ready to write data

thread- 3 has wrote the data: 4370

thread- 3 be ready to write data

thread- 3 has wrote the data: 1533

thread-4be ready to get data

thread-4get the data:  1533

thread- 5 be ready to write data

thread- 5 has wrote the data: 2345

thread-6be ready to get data

thread-6get the data:  2345

thread- 9 be ready to write data

thread- 9 has wrote the data: 9463

thread- 9 be ready to write data

thread- 9 has wrote the data: 9301

thread- 9 be ready to write data

thread- 9 has wrote the data: 549

thread- 9 be ready to write data

thread- 9 has wrote the data: 4673

thread- 9 be ready to write data

我们可以看到打印语句结果很正常。

下面我们再来实现一个模拟缓冲区的小demo:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

import java.util.hashmap;

import java.util.map;

import java.util.concurrent.locks.readwritelock;

import java.util.concurrent.locks.reentrantreadwritelock;

 

/*

  * @author vayne

  *

  * 多线程实现缓存的小demo

  */

class cachend

{

   volatile map<string, string> cachmap = new hashmap<string, string>(); //加volatile关键字保证可见性。

 

   readwritelock rwlock = new reentrantreadwritelock(); //这个读写锁要定义在方法外面,使得每一个线程用的是同一个读写锁。

   public string gets(string key)           //如果定义在方法内部,就是跟方法栈有关的读写锁。这样可能不是同一个锁。

   {

     rwlock.readlock().lock();

     string value = null ;

     try

     {

       value = cachmap.get(key);

 

       if (cachmap.get(key) == null ) //这里要重新获得key对应的value值

       {

         rwlock.readlock().unlock();

         rwlock.writelock().lock();

         try

         {

           if (cachmap.get(key) == null ) //这里也是

           {

             value = "" + thread.currentthread().getname();

 

             cachmap.put(key, value);

 

             system.out.println(thread.currentthread().getname() + " put the value ::::" + value);

           }

         } finally

         {

           rwlock.readlock().lock();  //将锁降级,这里跟下一句的顺序不能反。

           rwlock.writelock().unlock(); //关于这里的顺序问题,下面我会提到。

         }

       }

 

     } finally

     {

       rwlock.readlock().unlock();

     }

 

     return cachmap.get(key);

   }

}

 

public class cachenddemo

{

   public static void main(string[] args)

   {

     cachend ca = new cachend();

     for ( int i = 0 ; i < 4 ; i++)

     {

       new thread( new runnable()

       {

         @override

         public void run()

         {

           system.out.println(thread.currentthread().getname()+ " " +ca.gets( "demo1" ));

           system.out.println(thread.currentthread().getname()+ " " +ca.cachmap.entryset());

         }

       }).start();

     }

   }

}

运行结果:

?

1

2

3

4

5

6

7

8

9

thread- 0 put the value ::::thread- 0

thread- 0 thread- 0

thread- 0 [demo1=thread- 0 ]

thread- 2 thread- 0

thread- 2 [demo1=thread- 0 ]

thread- 3 thread- 0

thread- 3 [demo1=thread- 0 ]

thread- 1 thread- 0

thread- 1 [demo1=thread- 0 ]

上面我给出了一些注释,其实这个代码是很不好写的,考虑的东西很多。下面我来讲一下上面的代码中提到的顺序问题。

对于读写锁我们应该了解下面的一些性质(这些性质是由源代码得出来的,因为源代码的设计,所以才有下列性质):

如果存在读锁,则写锁不能被获取,原因在于:读写锁要确保写锁的操作对读锁可见。,如果允许读锁在已被获取的情况下对写锁的获取,那么正在运行的其他读线程就无法感知到当前写线程的操作。因此,只有等待其他读线程都释放了读锁,写锁才能被当前线程获取,而写锁一旦被获取,则其他读写线程的后续访问将会被阻塞。 锁降级:指的是写锁降级成为读锁。具体操作是获取到写锁之后,在释放写锁之前,要先再次获取读锁。这也就是上面我写注释提醒大家注意的地方。为什么要这样处理呢,答案就是为了保证数据可见性。如果当前线程不获取读锁而是直接释放写锁,假设此刻另一个线程(记作t)获取了写锁并修改了数据,那么当前线程无法感知线程t的数据更新。如果当前线程获取读锁,即遵循锁降级的步骤,则线程t将会被阻塞,知道当前线程使用数据并释放读锁之后,t才能获取写锁进行数据更新。

第二条对应我们上面的程序就是,如果我们添加了[demo1]对应的value值,然后释放了写锁,此时在当前线程s还未获得读锁时,另一个线程t又获得了写锁,那么就会将s的操作给覆盖(如果取到的值已经缓存在s中,那么t的操作就无法被s感知了,到最后依然会返回s操作的值)。

再来看一个demo:

读写锁,分为读锁和写锁,多个读锁不互斥,读锁和写锁互斥,写锁与写锁互斥,这是jvm自己控制的,你只要上好相应的锁即可,如果你的代码只读数据,可以很多人同时读,但不能同时写,那就上读锁;如果你的代码修改数据,只能有一个人在写,且不能同时读取,那就上写锁.总之,读的时候上读锁,写的时候上写锁!

看如下程序: 新建6个线程,3个线程用来读,3个线程用来写,

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

package javaplay.thread.test;

 

import java.util.random;

import java.util.concurrent.locks.readwritelock;

import java.util.concurrent.locks.reentrantreadwritelock;

 

public class readwritelocktest {

   public static void main(string[] args) {

     final queue3 q3 = new queue3();

     for ( int i = 0 ; i < 3 ; i++) {

       new thread() {

         public void run() {

           while ( true ) {

             q3.get();

           }

         }

       }.start();

       new thread() {

         public void run() {

           while ( true ) {

             q3.put( new random().nextint( 10000 ));

           }

         }

       }.start();

     }

   }

}

 

class queue3 {

   private object data = null ; // 共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。

   // 读写锁

   readwritelock rwl = new reentrantreadwritelock();

 

   // 相当于读操作

   public void get() {

     rwl.readlock().lock();

     try {

       system.out.println(thread.currentthread().getname() + " be ready to read data!" );

       thread.sleep(( long ) (math.random() * 1000 ));

       system.out.println(thread.currentthread().getname() + "have read data :" + data);

     } catch (interruptedexception e) {

       e.printstacktrace();

     } finally {

       rwl.readlock().unlock();

     }

   }

 

   // 相当于写操作

   public void put(object data) {

     rwl.writelock().lock();

     try {

       system.out.println(thread.currentthread().getname() + " be ready to write data!" );

       thread.sleep(( long ) (math.random() * 1000 ));

       this .data = data;

       system.out.println(thread.currentthread().getname() + " have write data: " + data);

     } catch (interruptedexception e) {

       e.printstacktrace();

     } finally {

       rwl.writelock().unlock();

     }

   }

}

读写锁功能很强大!这样可以实现正常的逻辑,如果我们把读写锁相关的代码注释,发现程序正准备写的时候,就有线程读了,发现准备读的时候,有线程去写,这样不符合我们的逻辑;通过java5的新特新可以很轻松的解决这样的问题;

查看java api reentrantreadwritelock 上面有经典(缓存)的用法,下面是doc里面的伪代码,,它演示的是一个实体的缓存,不是缓存系统,相当于缓存代理,注意volatile的运用:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

package javaplay.thread.test;

 

import java.util.concurrent.locks.reentrantreadwritelock;

 

/*

  * sample usages. here is a code sketch showing how to perform lock downgrading after updating a cache

  * (exception handling is particularly tricky when handling multiple locks in a non-nested fashion):

  */

class cacheddata {

   object data;

   volatile boolean cachevalid;

   final reentrantreadwritelock rwl = new reentrantreadwritelock();

 

   void processcacheddata() {

     rwl.readlock().lock();

     if (!cachevalid) {

       // must release read lock before acquiring write lock

       rwl.readlock().unlock();

       rwl.writelock().lock();

       try {

         // recheck state because another thread might have

         // acquired write lock and changed state before we did.

         if (!cachevalid) {

           data = ...

           cachevalid = true ;

         }

         // downgrade by acquiring read lock before releasing write lock

         rwl.readlock().lock();

       } finally {

         rwl.writelock().unlock(); // unlock write, still hold read

       }

     }

 

     try {

       use(data);

     } finally {

       rwl.readlock().unlock();

     }

   }

}

假设现在多个线程来读了,那第一个线程读到的数据是空的,那它就要写就要填充数据,那么第二个第三个就应该互斥等着,一进来是来读数据的所以上读锁,进来后发现数据是空的,就先把读锁释放再重新获取写锁,就开始写数据,数据写完了,就把写锁释放,把读锁重新挂上,持有读锁时不能同时获取写锁,但拥有写锁时可同时再获取读锁,自己线程挂的写锁可同时挂读锁的,这就是降级,就是除了读锁和写锁外,还有读写锁也叫更新锁,就是自己即可以读又可以写的锁,也就是在自己拥有写锁还没释放写锁时就获取了读锁就降级为读写锁/更新锁,但是不能在持有读锁时再获取写锁;

基于上面的例子,我们可以实现一个缓存系统:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

package javaplay.thread.test;

 

import java.util.hashmap;

import java.util.map;

import java.util.concurrent.locks.readwritelock;

import java.util.concurrent.locks.reentrantreadwritelock;

 

public class cachedemo {

   private map<string, object> cache = new hashmap<>();

 

   public static void main(string[] args) {

 

   }

 

   // 可做到多个线程并必的读 读和写又互斥 系统性能很高

   // 这就是读写锁的价值

   private readwritelock rwl = new reentrantreadwritelock();

 

   public object getdata(string key) {

     rwl.readlock().lock();

     object value = null ;

     try {

       value = cache.get(key);

       if (value == null ) { // 避免首次多次查询要加synchronized

         rwl.readlock().unlock();

         rwl.writelock().lock();

         try {

           if (value == null ) // 就算第二个第三个线程进来时也不用再写了 跟伪代码相同原理

             value = "aaa" ; // 实际去query db

         } finally {

           rwl.writelock().unlock();

         }

         rwl.readlock().lock();

       }

     } finally {

       rwl.readlock().unlock();

     }

     return value;

   }

}

错误之处:没有把不存在的值put;要用get(key)来判空

感谢大家对的支持。

原文链接:https://www.cnblogs.com/pony1223/p/9428248.html

查看更多关于Java编程读写锁详解的详细内容...

  阅读:39次