




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、The New Java Technology Memory ModelJeremy Manson and William Pugh AudienceAssume you are familiar with basics of Java technology-based threads (“Java threads”)Creating, starting and joining threadsSynchronizationwait and notifyAllJava Thread SpecificationRevised as part of JSR-133 Part of the new J
2、ava Language Specand the Virtual Machine SpecFeatures talked about here today are in JDK1.5Not all of these ideas are guaranteed to work in previous versionsPrevious thread spec was brokenforbid optimizations performed by many JVMsSafety Issues in Multithreaded SystemsMany intuitive assumptions do n
3、ot holdSome widely used idioms are not safeOriginal Double-checked locking idiomChecking non-volatile flag for thread terminationCant use testing to check for errorsSome anomalies will occur only on some platformse.g., multiprocessorsAnomalies will occur rarely and non-repeatedlyRevising the Thread
4、SpecThe Java Thread Specification has undergone significant revisionMostly to correctly formalize existing behaviorBut a few changes in behaviorGoalsClear and easy to understandFoster reliable multithreaded codeAllow for high performance JVMsHas affected JVMsAnd badly written existing codeIncluding
5、parts of Suns JDKThis TalkDescribe building blocks of synchronization and concurrent programming in JavaBoth language primitives and util.concurrent abstractionsExplain what it means for code to be correctly synchronizedTry to convince you that clever reasoning about unsynchronized code is almost ce
6、rtainly wrongNot needed for efficient and reliable programsThis TalkWe will be talking mostly aboutsynchronized methods and blocksvolatile fields Same principles work with JSR-166 locks and atomic operationsWill also talk about final fields and immutability.TaxonomyHigh level concurrency abstraction
7、sJSR-166 and java.util.concurrentLow level lockingsynchronized() blocksLow level primitivesvolatile variables, java.util.concurrent.atomic classesallows for non-blocking synchronizationData races: deliberate undersynchronizationAvoid!Not even Doug Lea can get it rightThree Aspects of Synchronization
8、AtomicityLocking to obtain mutual exclusionVisibilityEnsuring that changes to object fields made in one thread are seen in other threadsOrderingEnsuring that you arent surprised by the order in which statements are executedDont Try To Be Too CleverPeople worry about the cost of synchronizationTry to
9、 devise schemes to communicate between threads without using synchronizationlocks, volatiles, or other concurrency abstractionsNearly impossible to do correctlyInter-thread communication without synchronization is not intuitiveQuiz Timex = y = 0 x = 1j = yThread 1y = 1i = xThread 2Can this result in
10、 i = 0 and j = 0?start threadsAnswer: Yes!x = y = 0 x = 1j = yThread 1y = 1i = xThread 2How can i = 0 and j = 0?start threadsHow Can This Happen?Compiler can reorder statementsOr keep values in registersProcessor can reorder themOn multi-processor, values not synchronized in global memoryThe memory
11、model is designed to allow aggressive optimizationincluding optimizations no one has implemented yetGood for performancebad for your intuition about insufficiently synchronized codeCorrectness and OptimizationsClever code that depends the order you think the system must do things in is almost always
12、 wrong in JavaDekkers Algorithm (first correct lock implementation) requires this orderingdoesnt work in Java, use supplied locksMust use synchronization to enforce visibility and orderingAs well as mutual exclusionIf you use synchronization correctly, you will not be able to see reorderingsSynchron
13、ization Actions(approximately)/ block until obtain locksynchronized(anObject) / get main memory value of field1 and field2 int x = anObject.field1;int y = anObject.field2; anObject.field3 = x+y;/ commit value of field3 to main memory/ release lockmoreCode();When Are Actions Visible to Other Threads?
14、glo = ref1unlock MThread 1lock Mref2 = gloThread 2lock Mref1.x = 1unlock Mj = ref2.xEverything beforean unlock (release)Is visible to everythingafter a later lock (acquire) on the same ObjectRelease and AcquireAll accesses before a releaseare ordered before and visible to any accesses after a matchi
15、ng acquireUnlocking a monitor/lock is a releasethat is acquired by any following lock of that monitor/lockOrderingRoach motel orderingCompiler/processor can move accesses into synchronized blocksCan only move them out under special circumstances, generally not observableSome special cases:locks on t
16、hread local objects are a no-opreentrant locks are a no-opVolatile fieldsIf a field could be simultaneously accessed by multiple threads, and at least one of those accesses is a writemake the field volatiledocumentationgives essential JVM guaranteesCan be tricky to get right, but nearly impossible w
17、ithout volatileWhat does volatile do?reads and writes go directly to memorynot cached in registersvolatile longs and doubles are atomicnot true for non-volatile longs and doublescompiler reordering of volatile accesses is restrictedroach motel semantics for volatiles and normalsno reordering for vol
18、atiles and volatilesVolatile release/acquireA volatile write is a releasethat is acquired by a later read of the same variableAll accesses before the volatile writeare ordered before and visible to all accesses after the volatile readclass Animator implements Runnable private volatile boolean stop =
19、 false; public void stop() stop = true; public void run() while (!stop) oneStep(); private void oneStep() /*.*/ Volatile guarantees visibilitystop must be declared volatileOtherwise, compiler could keep in register class Future private volatile boolean ready;private Object data;public Object get() i
20、f (!ready) return null;return data;Volatile guarantees orderingIf a thread reads data, there is a release/acquire on ready that guarantees visibility and ordering public synchronized void setOnce(Object o) if (ready) throw ; data = o;ready = true;Other Acquires and ReleasesOther actions form release
21、/acquire pairsStarting a thread is a releaseacquired by the run method of the threadTermination of a thread is a releaseacquired by any thread that joins with the terminated threadDefending against data racesAttackers can pass instances of your object to other threads via a data raceCan cause weird
22、things to be observedcould be observed in some JVMsin older JVMs, String objects might be seen to changechange from /tmp to /usrIf a class is security critical, must take stepsChoices:use synchronization (even in constructor)object can be made visible to multiple threads before constructor finishesm
23、ake object immutable by making all fields finalImmutable classesMake all critical fields finalDont allow other threads to see object until it is fully constructedJVM will be responsible for ensuring that object is perceived as immutableeven if malicious code uses data races to attack the classOptimi
24、zation of final fieldsNew spec allows aggressive optimization of final fieldshoisting of reads of final fields across synchronization and unknown method callsstill maintains immutabilityShould allow for future JVMs to obtain performance advantagesFinalizersOnly guaranteed to see writes that occur by
25、 the end of the objects constructor.If finalizer needs to see later writes, use synchronizationFields may be made final earlier than the program text might implySynchronization on object also keeps it aliveMultiple finalizers may be run concurrentlyBe careful to synchronize properly!Synchronize When
26、 Needed Places where threads interactNeed synchronizationMay need careful thoughtMay need documentationCost of required synchronization not significantFor most applicationsNo need to get trickySynchronized ClassesSome classes are synchronizedVector, Hashtable, StackMost Input/Output StreamsOverhead
27、of unneeded synchronization can be measurableContrast with Collection classesBy default, not synchronizedCan request synchronized versionOr can use java.util.concurrent versions (Queue, ConcurrentMap implementations)Using synchronized classesOften doesnt suffice for concurrent interactionSynchronize
28、d Collections Arent Always EnoughTransactions (DO NOT USE)Violate atomicityID getID(String name) ID x = h.get(name);if (x = null) x = new ID();h.put(name, x); return x; IteratorsCant modify collection while another thread is iterating through itConcurrent InteractionsOften need entire transactions t
29、o be atomicReading and updating a MapWriting a record to an OutputStreamOutputStreams are synchronizedCan have multiple threads trying to write to the same OutputStreamOutput from each thread is nondeterministically interleavedOften essentially uselessutil.concurrentThe stuff in java.util.concurrent
30、 is great, use itConcurrentHashMap has some additional features to get around problems with transactionsputIfAbsentconcurrent iterationCopyOnWrite classes allow concurrent iteration and non-blocking readsmodification is expensive, should be rareDesigning Fast CodeMake it right before you make it fas
31、tReduce synchronization costsAvoid sharing mutable objects across threadsavoid old Collection classes (Vector, Hashtable)use bulk I/O (or, even better, java.nio classes)Use java.util.concurrent classesdesigned for speed, scalability and correctnessAvoid lock contentionReduce lock scopesReduce lock d
32、urationsThings That Dont WorkThinking about memory barriersThere is nothing that gives you the effect of a memory barrierOriginal Double-Check IdiomAKA multithreaded lazy initializationAny unsynchronized non-volatile reads/writes of refsDepending on sleep for visibilityClever reasoning about cause and effect with respect to data racesSynchronization on Thread Local ObjectsSynchronization on thread local objects (objects that are only accessed by a single thread)has no semantics or meaningcompiler can remove itcan also remove reentr
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论