java內(nèi)存模型與多線程技術.ppt_第1頁
java內(nèi)存模型與多線程技術.ppt_第2頁
java內(nèi)存模型與多線程技術.ppt_第3頁
java內(nèi)存模型與多線程技術.ppt_第4頁
java內(nèi)存模型與多線程技術.ppt_第5頁
已閱讀5頁,還剩43頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

1、java內(nèi)存模型與多線程技術,yangjsalibaba-,主要內(nèi)容和目的,學習java多線程理論基礎:JMM(java內(nèi)存模型) 學習java多線程技術基礎:理解同步是如和工作 分析程序什么時候需要同步 澄清對volatile誤解,正確使用 Task Cancellation and Thread Shutdown策略 Lazy initialization Safety技術,JMM(java內(nèi)存模型),什么是Java內(nèi)存模型 Java內(nèi)存模型相關概念 java線程和內(nèi)存交互行為定義 Ordering /Thread 1 executes void to() a = 3; b = 4; /T

2、hread 2 executes void fro() System.out.println(a= + a + , b= + b); 類似計算機多級存儲器結(jié)構(gòu),Working Memory類似Cache機制 問題:變量a,b何時寫會main memory?,Ordering /Thread 1 executes void to() a = 3; /This can appear to happen second b = 4; / This can appear to happen first /Thread 2 executes void fro() System.out.println(a=

3、 + a + , b= + b); 下面哪種結(jié)果是正確的: a=1, b=2 a=1, b=4 a=3, b=2 a=3 ,b=4,Happens-Before Memory Model,類似釋放一致性模型 Partial ordering(happens-before) :如果B能夠看到A動作產(chǎn)生的結(jié)果,我們說A happens-before B,JMM定義了一些這樣的規(guī)則,如: Program order rule. Each action in a thread happens-before every action in that thread that comes later in

4、the program order. Monitor lock rule. An unlock on a 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 field ,The rules for happens-before,JMM相關java語言規(guī)范,JMM定義了保證內(nèi)存操作跨線程的正確

5、的Ordering和visibility 方法 Java語言提供的技術和工具 synchronized 塊 volatile 變量(在JDK5+的JVM中得到修補) 工具類:java.util.concurrent.locks 原子變量java.util.concurrent.atomic Final變量(在JDK5+的JVM中得到修補),正確的理解synchronized,synchronized 作用說明 Synchronized內(nèi)存模型語義分析 如何判定多線程的程序何時需要Synchronized 同步需求的JMM內(nèi)存交互分析練習 鎖對象的引用在同步塊中發(fā)生修改會出現(xiàn)什么? Hostsp

6、ot JVM的synchronized優(yōu)化技術 直接使用synchronized 不足之處,synchronized 作用說明,Low level locking 什么時候需要synchronized ? 一個變量有可能被多個線程訪問,其中至少有一個線程是寫操作 每個對象都有一個相關的lock對象(監(jiān)視器) java語言沒有提供分離的lock和unlock操作 ,但是在JVM提供了兩個單獨的指令monitorenter和monitorext來實現(xiàn) 特性 Atomicity :Locking to obtain mutual exclusion Visibility :Ensuring that

7、 changes to object fields made in one thread are seen in other threads(memory) Ordering: Ensuring that you arent surprised by the order in which statements are executed Blocking:Cant interrupt,Synchronized內(nèi)存模型語義分析,Synchronized:通過對象引用找到同步對象,然后獲取對象上的監(jiān)視器進行鎖操作 當線程進入synchronized 塊之后首先要做的是清洗 threads worki

8、ng memory, 對塊內(nèi)使用到的變量要么執(zhí)行assign動作要么對use的變量執(zhí)行 read-load原子操作從 main memory裝載新的值 當線程退出synchronized 塊之前,對它在working memory中所有的 assigned values執(zhí)行 store write原子操作,寫回main memory,Synchronized內(nèi)存模型語義分析,Example: / block until obtain lock synchronized(obj) / get main memory value of field1 and field2 int x = obj.f

9、ield1; int y = obj.field2; obj.field3 = x+y; / commit value of field3 to main memory / release lock,如何分析多線程并發(fā)需求,class SynchSimple int a = 1, b = 2; /Thread 1 executes synchronized void to() a = 3; b = 4; /Thread 2 executes void fro() System.out.println(a= + a + , b= + b); 以下哪種結(jié)果是正確的? a=1, b=2 a=1, b

10、=4 a=3, b=2 a=3 ,b=4 這是一個線程安全的類嗎? 接下來我們通過JMM語義來分析這個例子,JMM內(nèi)存交互分析,JMM內(nèi)存交互分析,SynchSimple 分析: write a 和 write b 在synchronized 規(guī)則中并沒有規(guī)定發(fā)生的順序約束 read a 和 read b. 同樣也沒有規(guī)定發(fā)生的順序 結(jié)果說明的什么問題?對一個方法聲明synchronized 并不能夠保證這個方法行為產(chǎn)生的結(jié)果是一個原子操作,也就是說write a 和 write b 兩個操作在main memory不是原子行為,雖然單個都是原子操作。,下面我們做一個練習:,JMM內(nèi)存交互分析

11、練習,Example: class Foo int a = 1, b = 2; synchronized void to() a = 3; b = 4; synchronized void fro() System.out.println(a= + a + , b= + b); 分析結(jié)果是什么?,問題?,這個方法的同步塊有可能被多個線程并發(fā)執(zhí)行! 有可能在intArr.length size的條件下獲得兩把不同的鎖,鎖對象的引用在同步塊中發(fā)生修改會出現(xiàn)什么? public void foo(int isze) synchronized(intArr) if(intArr.length size

12、) int newIntArr = new intsize; System.arraycopy(intArr,0,newIntArr,0,intArr.length); intArr = newintArr; ,直接使用synchronized 不足之處和發(fā)展,不能夠擴越多個對象 當在等待鎖對象的時候不能中途放棄,直到成功 等待沒有超時限制 Terrupt()不能中斷阻塞 JDK5中提供更加靈活的機制:Lock和Condition synchronized在JDK6中性能將會有很大提升,Hostspot JVM的synchronized優(yōu)化技術,鎖省略:鎖對象的引用時線程本地

13、對象(線程的堆棧內(nèi)的對象) public String getStoogeNames() Vector v = new Vector(); v.add(Moe); v.add(Larry); v.add(Curly); return v.toString(); ,Hostspot JVM的synchronized優(yōu)化技術,鎖粗化:鎖粗化就是把使用同一鎖對象的相鄰同步塊合并的過程 public void addStooges(Vector v) v.add(Moe); v.add(Larry); v.add(Curly); ,Hostspot JVM的synchronized優(yōu)化技術,自適應鎖優(yōu)

14、化技術 實現(xiàn)阻塞有兩種的技術,即讓操作系統(tǒng)暫掛線程,直到線程被喚醒,或者使用旋轉(zhuǎn)(spin) 鎖。旋轉(zhuǎn)鎖基本上相當于以下代碼: while (lockStillInUse) ; Hotspot JVM可以對持有時間短的鎖使用旋轉(zhuǎn),對持有時間長的鎖使用暫掛。,理解和使用Volatile變量,Volatile變量的內(nèi)存模型分析 使用valatile JDK5的util.concurrent.atomic,Volatile變量的內(nèi)存模型分析,“不要相信volatile ”,這種說法已經(jīng)過時 舊的內(nèi)存模型:保證讀寫volatile都直接發(fā)生在main memory中,線程的working memory

15、不進行緩存 僅僅保證這些volatile使用的價值和意義不大 在新的內(nèi)存模型下對volatile的語義進行了修補和增強 如果當線程 A 寫入 volatile 變量 V 而線程 B 讀取 V 時,那么在寫入 V 時,A 可見的所有變量值現(xiàn)在都可以保證對 B 是可見的。結(jié)果就是作用更大的 volatile 語義,代價是訪問 volatile 字段時會對性能產(chǎn)生了一點點的影響。(A volatile var write happens-before read of the var),Volatile變量的內(nèi)存模型分析,volatile 的舊語義只承諾正在讀和寫的變量的可見性,仍然參與排序。這樣導致

16、排序問題。新的內(nèi)存模型修補了這一點 實際上,對 volatile 字段的每一次讀或者寫都像是“半個”同步。 對 volatile 的讀有與monitor enter的內(nèi)存語義, 對 volatile 的寫有與monitor exit的同樣的語義。,Volatile Guarantees Visibility,Stop 用volatile修飾來保證變量的寫可見性 class Task implements Runnable private volatile boolean stop = false; public void stop() stop = true; public void run(

17、) while (!stop) runTask(); try Thread.sleep(100); ; private void runTask() /*.*/ ,Volatile Guarantees Ordering,If a thread reads data, 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),使用valatile,vo

18、latile 變量+操作不是原子行為 volatile int x= 1; x+;/不是一個原子操作,需要多條指令 Volatile 變量比 synchronization要便宜很多 在jdk5中推薦采用 util.concurrent.atomic 工作機制類似Volatile 同時提供了簡單運算的原子行為,JDK5的util.concurrent.atomic,get() 具有讀取 volatile 變量的內(nèi)存效果。 set() 具有寫入(分配) volatile 變量的內(nèi)存效果 支持操作: getAndSet getAndAdd addAndGet getAndDecrement get

19、AndIncrement decrementAndGet incrementAndGet 只要你有足夠的能力,用Atomic變量能夠?qū)崿F(xiàn)所有的同步,Cancellation and Shutdown,Cancellation and Shutdown Task cancellation policy 設計 Cancellation policy :Interruption 正確處理InterruptedException,Cancellation and Shutdown,clean up any work then terminate.(Safe terminate) 為什么需要cancel

20、lable (中斷正在進行的活動) User-requested cancellation Time-limited activities Application events Errors Shutdown 安全快速可靠結(jié)束一個線程是一個比較復雜的話題 Java沒有提供安全的強迫一個Thread結(jié)束的方法 Java provides interruption, a cooperative mechanism,cancellation policy 設計,How: how other code can request cancellation When:when the task checks

21、 whether cancellation has been requested What:what actions the task takes in response to a cancellation request.,Example: cancellation policy 設計,class Task implements Runnable private volatile boolean stop = false; public void stop() stop = true; public void run() while (!stop) runTask(); try Thread

22、.sleep(100); ; private void runTask() /*.*/ ,Example: cancellation policy 設計分析,How,When,How? 問題: polling loops,只有一個檢查點 線程不能立刻結(jié)束,要等到檢測的時候 遇到Blocking method有可能無法中止 檢查的變量必須是volatile修飾的,Cancellation policy :Interruption,禮貌地勸告另一個線程在它愿意并且方便的時候停止它正在做的事情。(Interruption is a cooperative mechanism ) Thread中斷狀態(tài)

23、(interrupted status):線程的一個內(nèi)部屬性,類型:boolean,初始值:false. Terrupt():設置interrupted status 為true,interruption Policy 分析,分析: How:Terrupt()方法. interrupt() 只是設置線程的中斷狀態(tài)。表示當前線程應該停止運行。 When:在 Thread.sleep()、 Thread.join() 或 Object.wait()等方法中取消阻塞并拋出 InterruptedException,也可以程序檢測: 輪詢中斷狀態(tài):Thread.is

24、Interrupted() 讀取并清除:Terrupted() InterruptibleChannel (java.nio):Most standard Channels implement InterruptibleChannel 等待獲取文件鎖定時可以被另一個線程中斷,Cancellation policy :Interruption,Interruption is usually the most sensible way to implement cancellation 其他問題 不能打斷一些IO操作,比如文件操作 無法終止在synchronized塊上鎖住的Th

25、read Synchronous socket I/O in java.io,InterruptedException,檢查型異常:java.lang.InterruptedException 當線程在很長一段時間內(nèi)一直處于正在等待、休眠或暫停狀態(tài)(Object.wait(), Object.wait(long), Object.wait(long, int), Thread.sleep(long)),而另一個線程用 Thread 類中的 interrupt 方法中斷它時,拋出該異常。 阻塞(blocking)方法 方法簽名包括拋出 InterruptedException,調(diào)用一個阻塞方法則

26、意味著這個方法也是一個阻塞方法 當中斷阻塞方法時,拋出InterruptedException Thread 在 Thread.sleep() 和 Object.wait() 等方法中支持的取消機制,表明可以提前返回。 當一個阻塞方法檢測到中斷并拋出 InterruptedException 時,它清除中斷狀態(tài),如何處理InterruptedException,錯誤的做法:swallow interruption requests try Task task = queue.take(); task.execute(); catch (InterruptedException e) log.e

27、rror(); ,如何處理InterruptedException,Restore the interrupt 如果真的要湮滅InterruptedException,應該保留被別人中斷的證據(jù),交給高層去決定。 /恰當?shù)淖龇ǎ?try Task task = queue.take(); task.execute(); catch (InterruptedException e) log.error(); Thread.currentThread().interrupt(); Propagate the InterruptedException 重新拋出它 ,如果拋到頂層,可以結(jié)束當前線程,Double-Checked Locking,目的:在多線程應用中用來lazy initialization并保證Singlen 在java語言中DCL不成立 / Broken multithreaded version

溫馨提示

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

評論

0/150

提交評論