Java中的同步问题

多线程编程中,特别是在多核时代,各种程序优化诸如乱序执行等,如何严格确保数据在多线程间共享访问的处理顺序,相关同步的API很关键,理解原理对于编写正确安全的多线程程序非常重要。本文对于多线程执行进行的设计模式归纳,把常用的编程模型用java语言进行了演示。
展开查看详情

1.Synchronization 1

2.Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2

3.Overview synchronization mechanism in Java RTE Visibility and re-ordering Design patterns to avoid safety issues: monitor pattern. client side locking. class composition. version iterattor . 3

4.Java Synchronization - concurrent objects safety threads which access the same object concurrently. safety - synchronize access to internal state of the object 4

5.class Even 5

6.if threads can access internal state of object concurrently - not safe @invariant is not guaranteed code perfectly safe in sequential environment 6

7.Visibility and Reordering – unsafe constructs in concurrent execution Visibility - when threads see values written to memory by other threads Reordering - compiler / RTE change code to optimize it 7

8.8

9.anonymous class - class that has no name combines class declaration and instance creation in one step in-line allows "on the fly" creation of object reduce the number of .java files necessary class used in specific situation: Comparator compiler will create separate class files: ClassName$SomeNumber.class 9

10.anonymous class - class that has no name Rules: always extend a super class or implement an interface implement all abstract methods in super class or interface. uses default constructor from the super class to create an instance 10

11.Inlining 11

12.Inlining Inline expansion - compiler optimization that replaces a function call site with the body of the callee . improve time and space usage at runtime, at cost of binary file size 12

13.13

14.output = 0 thread t does not "see" the change to the state of d performed in main thread thread main - implicitly created by JVM executes main() method main calls  d.set (10): 10 is written to memory:  i _ member of: VisibilityDemo  object t reads from i _ ( d.get () ) Java does not guarantee t sees most recent value written to this memory location 14

15.Re-ordering compiler must be able to re-order simple instructions to optimize our code 15

16.Re-ordering compiler guarantees safe reordering in non-concurrent execution environments. order of operations is that the sequence will end with operation 4 16

17.Re-ordering in concurrent environments, reordering may harm 17

18.“must-happen-before” compiler would not reorder if "must-happen-before" constraint 18

19.“must-happen-before” "must-happen-before“ - call to any (non-inline) function compiler would not go recursively into that function 19

20.“must-happen-before” "must-happen-before“ - call to any (non-inline) function compiler would not go recursively into that function 19

21.synchronized Java coordinates actions of threads on object: keyword  before method name in class definition: public synchronized int add() - only one thread is allowed to enter constructors cannot be synchronized - syntax error ( only thread that creates an object access its constructor ) 21

22.synchronized Java RTE ensures that only one thread access this method. solves visibility and reordering problems; " write " to memory during synchronized code section is guaranteed to be returned to all " read " operations following it 22

23.How "synchronized" is implemented? Java mechanism - use it better / avoid common pitfalls each object inside JVM (at runtime) has a lock ("monitor") JVM maintain/initialize locks. cannot access locks explicitly access implicitly using synchronized   23

24.locks locks are in one of two states; in possession of thread available thread T tries to acquire the lock of any object. if available – lock transferred to T possession otherwise, T sleeps ( queue) until lock available T wakes up and tries to acquire lock 24

25.synchronized each thread, calling the method, must first acquire lock. when thread exits – thread releases lock 25

26.The cost of locks – time, concurrency memory sync.: after thread exits – memory of all threads synchronize with main memory   thread may cache copies of memory in its own memory (e.g., CPU registers / CPU cache) blocking: threads must wait for each other 26

27.When to Use Synchronization mutable variable accessible from different threads must be protected with lock else, you may be hit by re-ordering problems monitor pattern - internal state of object is encapsulated . objects are responsible to synchronize access to state: synchronized get() /set()   27

28.When to Use Synchronization invariant involving several members - synchronized with same lock. never lock large parts of code. minimize code sections which use locking 28

29.Synchronized Properties synchronized keyword is not part of the method signature. synchronized keyword cannot be specified in an interface. constructors cannot be  synchronized no point - as long as constructor is not complete, object instance is not accessible to other threads, unless… static method as synchronized - lock associated with the class to be used (each class in Java is also an object on its own) Java locks are Reentrant : same thread holding the lock can get it again and again. 29