內存模型與多線程技術_第1頁
內存模型與多線程技術_第2頁
內存模型與多線程技術_第3頁
內存模型與多線程技術_第4頁
內存模型與多線程技術_第5頁
已閱讀5頁,還剩43頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、java內存模型與多線程技術yangjs主要內容和目的學習java多線程理論基礎:JMM(java內存模型)學習java多線程技術基礎:理解同步是如和工作 分析程序什么時候需要同步澄清對volatile誤解,正確使用Task Cancellation and Thread Shutdown策略Lazy initialization Safety技術2JMM(java內存模型)什么是Java內存模型Java內存模型相關概念java線程和內存交互行為定義Ordering&visibilityJMM相關java語言規范3內存模型操作平臺的內存模型寄存器,CPU緩存,物理內存,虛擬內存緩存一致性模型順

2、序一致性模型:要求對某處理機所寫的值立即進行傳播,在確保該值以被所有處理機接受后才能繼續其他指令的執行釋放一致性模型:允許將某處理機所寫的值延遲到釋放鎖時進行傳播4Java內存模型(JMM)內存存管理的跨平臺統一的模型 write-once, run-anywhere concurrent applications in Java定義了Java線程和內存交互的規則通過一組語義規則來描述尤其是多線程之間共享內存的模式,保證多線程程序結果的可預測,語義一致 性不同于其他語言,同平臺無關所有的實例變量,靜態變量和數組元素都存放在堆內存里線程本地變量在堆棧中,不受JMM影響5Java內存模型相關概念T

3、hread working copy memory在java規范中這是一個抽象的概念,對應可能會是寄存器,cpu緩存,編譯及執行優化等 。一個新產生的Thread有一個空的working memory。類似一個高速緩存線程之間無法相互直接訪問,變量傳遞均需要通過主存完成 The main memory 就是我們所說的java堆內存 Threads execution engine保證線程的正確執行順序6java線程和內存交互行為定義JLS中對線程和主存互操作定義了6個行為,分別為load,save,read,write,assign和use,這些操作行為具有原子性,且相互依賴,有明確的調用先后

4、順序A use action (by a thread) transfers the contents of the threads working copy of a variable to the threads execution engine. An assign action (by a thread) transfers a value from the threads execution engine into the threads working copy of a variable. A read action (by the main memory) transmits

5、the contents of the master copy of a variable to a threads working memory for use by a later load operation. A load action (by a thread) puts a value transmitted from main memory by a read action into the threads working copy of a variable. A store action (by a thread) transmits the contents of the

6、threads working copy of a variable to main memory for use by a later write operation. A write action (by the main memory) puts a value transmitted from the threads working memory by a store action into the master copy of a variable in main memory. 7java線程和內存交互分析例子分析:class Simple int a = 1, b = 2;/Th

7、read 1 executesvoid to() a = 3; b = 4; /Thread 2 executesvoid fro() System.out.println(a= + a + , b= + b);類似計算機多級存儲器結構,Working Memory類似Cache機制問題:變量a,b何時寫會main memory?8Ordering&visibility 程序順序: 程序聲明它們應當發生的順序 執行順序:JMM不保證線程對變量操作發生的順序和被其他線程看到的是同樣的順序。 JMM容許線程以寫入變量時所不相同的次序把變量存入主存 線程內部本身遵循程序順序,從線程外看到的是執行順序

8、編譯器和處理器可能會為了性能優化,進行重新排序程序執行為了優化也可能重新排序9Ordering&visibility多線程場景分析class Simple int a = 1, b = 2;/Thread 1 executesvoid to() a = 3; /This can appear to happen secondb = 4; / This can appear to happen first/Thread 2 executesvoid fro() System.out.println(a= + a + , b= + b);下面哪種結果是正確的: a=1, b=2 a=1, b=4a

9、=3, b=2a=3 ,b=410Happens-Before Memory Model類似釋放一致性模型Partial ordering(happens-before) :如果B能夠看到A動作產生的結果,我們說A happens-before B,JMM定義了一些這樣的規則,如:Program order rule. Each action in a thread happens-before every action in that thread that comes later in the program order.Monitor lock rule. An unlock on a

10、monitor lock happens-before every subsequent lock on that same monitor lock.Volatile variable rule. A write to a volatile field happens-before every subsequent read of that same field11The rules for happens-before 12JMM相關java語言規范JMM定義了保證內存操作跨線程的正確的Ordering和visibility 方法Java語言提供的技術和工具synchronized 塊vo

11、latile 變量(在JDK5+的JVM中得到修補)工具類:java.util.concurrent.locks原子變量java.util.concurrent.atomicFinal變量(在JDK5+的JVM中得到修補)13正確的理解synchronizedsynchronized 作用說明Synchronized內存模型語義分析如何判定多線程的程序何時需要Synchronized同步需求的JMM內存交互分析練習鎖對象的引用在同步塊中發生修改會出現什么?Hostspot JVM的synchronized優化技術直接使用synchronized 不足之處14synchronized 作用說明L

12、ow level locking什么時候需要synchronized ?一個變量有可能被多個線程訪問,其中至少有一個線程是寫操作每個對象都有一個相關的lock對象(監視器)java語言沒有提供分離的lock和unlock操作 ,但是在JVM提供了兩個單獨的指令monitorenter和monitorext來實現特性Atomicity :Locking to obtain mutual exclusionVisibility :Ensuring that changes to object fields made in one thread are seen in other threads(m

13、emory)Ordering: Ensuring that you arent surprised by the order in which statements are executedBlocking:Cant interrupt 15Synchronized內存模型語義分析Synchronized:通過對象引用找到同步對象,然后獲取對象上的監視器進行鎖操作當線程進入synchronized 塊之后首先要做的是清洗 threads working memory, 對塊內使用到的變量要么執行assign動作要么對use的變量執行 read-load原子操作從 main memory裝載新的

14、值當線程退出synchronized 塊之前,對它在working memory中所有的 assigned values執行 store write原子操作,寫回main memory 16Synchronized內存模型語義分析Example: / block until obtain locksynchronized(obj) / get main memory value of field1 and field2 int x = obj.field1; int y = obj.field2; obj.field3 = x+y;/ commit value of field3 to mai

15、n memory/ release lock17如何分析多線程并發需求class SynchSimple int a = 1, b = 2;/Thread 1 executessynchronized void to() a = 3;b = 4; /Thread 2 executesvoid fro() System.out.println(a= + a + , b= + b);以下哪種結果是正確的?a=1, b=2 a=1, b=4a=3, b=2a=3 ,b=4這是一個線程安全的類嗎?接下來我們通過JMM語義來分析這個例子18JMM內存交互分析19JMM內存交互分析SynchSimple

16、分析:write a 和 write b 在synchronized 規則中并沒有規定發生的順序約束 read a 和 read b. 同樣也沒有規定發生的順序結果說明的什么問題?對一個方法聲明synchronized 并不能夠保證這個方法行為產生的結果是一個原子操作,也就是說write a 和 write b 兩個操作在main memory不是原子行為,雖然單個都是原子操作。下面我們做一個練習:20JMM內存交互分析練習Example:class Fooint a = 1, b = 2;synchronized void to() a = 3;b = 4;synchronized void

17、 fro() System.out.println(a= + a + , b= + b);分析結果是什么?21問題?這個方法的同步塊有可能被多個線程并發執行!有可能在intArr.length size的條件下獲得兩把不同的鎖 鎖對象的引用在同步塊中發生修改會出現什么?public void foo(int isze)synchronized(intArr)if(intArr.length size)int newIntArr = new intsize;System.arraycopy(intArr,0,newIntArr,0,intArr.length);intArr = newintAr

18、r; 22直接使用synchronized 不足之處和發展不能夠擴越多個對象當在等待鎖對象的時候不能中途放棄,直到成功等待沒有超時限制Terrupt()不能中斷阻塞JDK5中提供更加靈活的機制:Lock和Conditionsynchronized在JDK6中性能將會有很大提升23Hostspot JVM的synchronized優化技術鎖省略:鎖對象的引用時線程本地對象(線程的堆棧內的對象)public String getStoogeNames() Vector v = new Vector(); v.add(Moe); v.add(Larry); v.add(Curly); return

19、v.toString(); 24Hostspot JVM的synchronized優化技術鎖粗化:鎖粗化就是把使用同一鎖對象的相鄰同步塊合并的過程public void addStooges(Vector v) v.add(Moe); v.add(Larry); v.add(Curly); 25Hostspot JVM的synchronized優化技術自適應鎖優化技術實現阻塞有兩種的技術,即讓操作系統暫掛線程,直到線程被喚醒,或者使用旋轉(spin) 鎖。旋轉鎖基本上相當于以下代碼: while (lockStillInUse);Hotspot JVM可以對持有時間短的鎖使用旋轉,對持有時間長

20、的鎖使用暫掛。26理解和使用Volatile變量Volatile變量的內存模型分析使用valatileJDK5的util.concurrent.atomic27Volatile變量的內存模型分析“不要相信volatile ”,這種說法已經過時舊的內存模型:保證讀寫volatile都直接發生在main memory中,線程的working memory不進行緩存 僅僅保證這些volatile使用的價值和意義不大在新的內存模型下對volatile的語義進行了修補和增強如果當線程 A 寫入 volatile 變量 V 而線程 B 讀取 V 時,那么在寫入 V 時,A 可見的所有變量值現在都可以保證對

21、 B 是可見的。結果就是作用更大的 volatile 語義,代價是訪問 volatile 字段時會對性能產生了一點點的影響。(A volatile var write happens-before read of the var) 28Volatile變量的內存模型分析volatile 的舊語義只承諾正在讀和寫的變量的可見性,仍然參與排序。這樣導致排序問題。新的內存模型修補了這一點實際上,對 volatile 字段的每一次讀或者寫都像是“半個”同步。對 volatile 的讀有與monitor enter的內存語義,對 volatile 的寫有與monitor exit的同樣的語義。 29Vo

22、latile Guarantees VisibilityStop 用volatile修飾來保證變量的寫可見性class Task implements Runnable private volatile boolean stop = false;public void stop() stop = true; public void run() while (!stop)runTask();try Thread.sleep(100); ;private void runTask() /*.*/ 30Volatile Guarantees OrderingIf a thread reads dat

23、a, there is a happens-before edge from write to read of ready that guarantees visibility of data (A volatile ready write happens-before read of the ready)31使用valatile volatile 變量+操作不是原子行為volatile int x= 1;x+;/不是一個原子操作,需要多條指令Volatile 變量比 synchronization要便宜很多在jdk5中推薦采用 util.concurrent.atomic 工作機制類似Vol

24、atile同時提供了簡單運算的原子行為32JDK5的util.concurrent.atomicget() 具有讀取 volatile 變量的內存效果。 set() 具有寫入(分配) volatile 變量的內存效果 支持操作:getAndSetgetAndAddaddAndGetgetAndDecrementgetAndIncrementdecrementAndGetincrementAndGet只要你有足夠的能力,用Atomic變量能夠實現所有的同步33Cancellation and ShutdownCancellation and Shutdown Task cancellation

25、policy 設計Cancellation policy :Interruption正確處理InterruptedException34Cancellation and Shutdownclean up any work then terminate.(Safe terminate)為什么需要cancellable (中斷正在進行的活動)User-requested cancellation Time-limited activities Application events Errors Shutdown 安全快速可靠結束一個線程是一個比較復雜的話題Java沒有提供安全的強迫一個Thread

26、結束的方法Java provides interruption, a cooperative mechanism 35cancellation policy 設計How: how other code can request cancellation When:when the task checks whether cancellation has been requested What:what actions the task takes in response to a cancellation request. 36Example: cancellation policy 設計cla

27、ss Task implements Runnable private volatile boolean stop = false;public void stop() stop = true; public void run() while (!stop)runTask();try Thread.sleep(100); ;private void runTask() /*.*/ 37Example: cancellation policy 設計分析How,When,How?問題:polling loops,只有一個檢查點線程不能立刻結束,要等到檢測的時候遇到Blocking method有可

28、能無法中止檢查的變量必須是volatile修飾的38Cancellation policy :Interruption 禮貌地勸告另一個線程在它愿意并且方便的時候停止它正在做的事情。(Interruption is a cooperative mechanism )Thread中斷狀態(interrupted status):線程的一個內部屬性,類型:boolean,初始值:false.Terrupt():設置interrupted status 為true39interruption Policy 分析分析:How:Terrupt()方法. interrupt() 只是設置線程的中斷狀態。表

29、示當前線程應該停止運行。When:在 Thread.sleep()、 Thread.join() 或 Object.wait()等方法中取消阻塞并拋出 InterruptedException,也可以程序檢測:輪詢中斷狀態:Thread.isInterrupted()讀取并清除:Terrupted() InterruptibleChannel (java.nio):Most standard Channels implement InterruptibleChannel 等待獲取文件鎖定時可以被另一個線程中斷40Cancellation policy :InterruptionInterrup

30、tion is usually the most sensible way to implement cancellation其他問題不能打斷一些IO操作,比如文件操作無法終止在synchronized塊上鎖住的ThreadSynchronous socket I/O in java.io 41InterruptedException 檢查型異常:java.lang.InterruptedException 當線程在很長一段時間內一直處于正在等待、休眠或暫停狀態(Object.wait(), Object.wait(long), Object.wait(long, int), Thread.s

31、leep(long)),而另一個線程用 Thread 類中的 interrupt 方法中斷它時,拋出該異常。阻塞(blocking)方法 方法簽名包括拋出 InterruptedException,調用一個阻塞方法則意味著這個方法也是一個阻塞方法 當中斷阻塞方法時,拋出InterruptedException Thread 在 Thread.sleep() 和 Object.wait() 等方法中支持的取消機制,表明可以提前返回。當一個阻塞方法檢測到中斷并拋出 InterruptedException 時,它清除中斷狀態42如何處理InterruptedException錯誤的做法:swall

32、ow interruption requeststry Task task = queue.take(); task.execute(); catch (InterruptedException e) log.error(); 43如何處理InterruptedExceptionRestore the interrupt如果真的要湮滅InterruptedException,應該保留被別人中斷的證據,交給高層去決定。/恰當的做法: try Task task = queue.take(); task.execute(); catch (InterruptedException e) log.error(); Thread.currentThread().interrup

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論