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

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、java內(nèi)存模型與多線程技術(shù),yangjsalibaba-,主要內(nèi)容和目的,學(xué)習(xí)java多線程理論基礎(chǔ):JMM(java內(nèi)存模型) 學(xué)習(xí)java多線程技術(shù)基礎(chǔ):理解同步是如和工作 分析程序什么時(shí)候需要同步 澄清對(duì)volatile誤解,正確使用 Task Cancellation and Thread Shutdown策略 Lazy initialization Safety技術(shù),JMM(java內(nèi)存模型),什么是Java內(nèi)存模型 Java內(nèi)存模型相關(guān)概念 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); 類似計(jì)算機(jī)多級(jí)存儲(chǔ)器結(jié)構(gòu),Working Memory類似Cache機(jī)制 問(wèn)題:變量a,b何時(shí)寫會(huì)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動(dòng)作產(chǎn)生的結(jié)果,我們說(shuō)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相關(guān)java語(yǔ)言規(guī)范,JMM定義了保證內(nèi)存操作跨線程的正確

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

6、ot JVM的synchronized優(yōu)化技術(shù) 直接使用synchronized 不足之處,synchronized 作用說(shuō)明,Low level locking 什么時(shí)候需要synchronized ? 一個(gè)變量有可能被多個(gè)線程訪問(wèn),其中至少有一個(gè)線程是寫操作 每個(gè)對(duì)象都有一個(gè)相關(guān)的lock對(duì)象(監(jiān)視器) java語(yǔ)言沒(méi)有提供分離的lock和unlock操作 ,但是在JVM提供了兩個(gè)單獨(dú)的指令monitorenter和monitorext來(lái)實(shí)現(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)存模型語(yǔ)義分析,Synchronized:通過(guò)對(duì)象引用找到同步對(duì)象,然后獲取對(duì)象上的監(jiān)視器進(jìn)行鎖操作 當(dāng)線程進(jìn)入synchronized 塊之后首先要做的是清洗 threads worki

8、ng memory, 對(duì)塊內(nèi)使用到的變量要么執(zhí)行assign動(dòng)作要么對(duì)use的變量執(zhí)行 read-load原子操作從 main memory裝載新的值 當(dāng)線程退出synchronized 塊之前,對(duì)它在working memory中所有的 assigned values執(zhí)行 store write原子操作,寫回main memory,Synchronized內(nèi)存模型語(yǔ)義分析,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 這是一個(gè)線程安全的類嗎? 接下來(lái)我們通過(guò)JMM語(yǔ)義來(lái)分析這個(gè)例子,JMM內(nèi)存交互分析,JMM內(nèi)存交互分析,SynchSimple 分析: write a 和 write b 在synchronized 規(guī)則中并沒(méi)有規(guī)定發(fā)生的順序約束 read a 和 read b. 同樣也沒(méi)有規(guī)定發(fā)生的順序 結(jié)果說(shuō)明的什么問(wèn)題?對(duì)一個(gè)方法聲明synchronized 并不能夠保證這個(gè)方法行為產(chǎn)生的結(jié)果是一個(gè)原子操作,也就是說(shuō)write a 和 write b 兩個(gè)操作在main memory不是原子行為,雖然單個(gè)都是原子操作。,下面我們做一個(gè)練習(xí):,JMM內(nèi)存交互分析

11、練習(xí),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é)果是什么?,問(wèn)題?,這個(gè)方法的同步塊有可能被多個(gè)線程并發(fā)執(zhí)行! 有可能在intArr.length size的條件下獲得兩把不同的鎖,鎖對(duì)象的引用在同步塊中發(fā)生修改會(huì)出現(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ā)展,不能夠擴(kuò)越多個(gè)對(duì)象 當(dāng)在等待鎖對(duì)象的時(shí)候不能中途放棄,直到成功 等待沒(méi)有超時(shí)限制 Terrupt()不能中斷阻塞 JDK5中提供更加靈活的機(jī)制:Lock和Condition synchronized在JDK6中性能將會(huì)有很大提升,Hostspot JVM的synchronized優(yōu)化技術(shù),鎖省略:鎖對(duì)象的引用時(shí)線程本地

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

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

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

16、排序問(wèn)題。新的內(nèi)存模型修補(bǔ)了這一點(diǎn) 實(shí)際上,對(duì) volatile 字段的每一次讀或者寫都像是“半個(gè)”同步。 對(duì) volatile 的讀有與monitor enter的內(nèi)存語(yǔ)義, 對(duì) volatile 的寫有與monitor exit的同樣的語(yǔ)義。,Volatile Guarantees Visibility,Stop 用volatile修飾來(lái)保證變量的寫可見(jiàn)性 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+;/不是一個(gè)原子操作,需要多條指令 Volatile 變量比 synchronization要便宜很多 在jdk5中推薦采用 util.concurrent.atomic 工作機(jī)制類似Volatile 同時(shí)提供了簡(jiǎn)單運(yùn)算的原子行為,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 設(shè)計(jì) Cancellation policy :Interruption 正確處理InterruptedException,Cancellation and Shutdown,clean up any work then terminate.(Safe terminate) 為什么需要cancel

20、lable (中斷正在進(jìn)行的活動(dòng)) User-requested cancellation Time-limited activities Application events Errors Shutdown 安全快速可靠結(jié)束一個(gè)線程是一個(gè)比較復(fù)雜的話題 Java沒(méi)有提供安全的強(qiáng)迫一個(gè)Thread結(jié)束的方法 Java provides interruption, a cooperative mechanism,cancellation policy 設(shè)計(jì),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 設(shè)計(jì),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 設(shè)計(jì)分析,How,When,How? 問(wèn)題: polling loops,只有一個(gè)檢查點(diǎn) 線程不能立刻結(jié)束,要等到檢測(cè)的時(shí)候 遇到Blocking method有可能無(wú)法中止 檢查的變量必須是volatile修飾的,Cancellation policy :Interruption,禮貌地勸告另一個(gè)線程在它愿意并且方便的時(shí)候停止它正在做的事情。(Interruption is a cooperative mechanism ) Thread中斷狀態(tài)

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

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

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

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

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

溫馨提示

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

最新文檔

評(píng)論

0/150

提交評(píng)論