






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







This paper describes alternative memory semantics for Java pro- grams using an enriched version of the Commit/Reconcile/Fence (CRF) memory model [16]. It outlines a set of reasonable practices for safe multithreaded programming in Java. Our semantics allow a number of optimizations such as load reordering that are currently prohibited. Simple thread-local algebraic rules express the effects of optimizations at the source or bytecode level. The rules focus on reordering source-level operations; they yield a simple depen- dency analysis algorithm for Java. An instruction-by-instruction translation of Java memory operations into CRF operations cap- tures thread interactions precisely. The fine-grained synchroniza- tion of CRF means the algebraic rules are easily derived from the translation. CRF can be mapped directly to a modern architecture, and is thus a suitable target for optimizing memory coherence dur- ing code generation.
D.3 [ Software ]: Programming Languages; C.1.2 [ Processor Ar- chitectures ]: Multiprocessors; D.3.1 [ Programming Languages ]: Formal Definitions and Theory
Languages, standardization
Memory models, Java, commit/reconcile/fence, compilation
This paper describes research conducted at the Laboratory for Computer Science of the Massachusetts Institute of Technology. Funding for this work is provided in part by grants from Microsoft and NSF.
Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. OOPSLA 2000 Minneapolis, Minnesota USA Copyright 2000 ACM 0-89791-88-6/97/05 .. $5.
Java is the first widely-accepted computer language to contain language-level support for multithreaded programs running on mul- tiple processors. Java objects are shared between all threads; reads and writes performed in one thread must be visible in another thread. Thus, like any multithreaded language Java requires a memory mod- el , which explains the behavior of objects which are read and writ- ten by multiple threads. In this paper we present new semantics for Java memory operations in terms of an enriched version of the Commit/Reconcile/Fence (CRF) memory model. These semantics are both simpler and more formal than the current Java semantics. At the same time, it retains a constructive, program-like flavor, de- scribing rather than prescribing program behavior. It should be emphasized that the details of the Java Memory Model are relevant to every single Java programmer. The memory model affects every object which may be visible to more than one thread during program execution. Writing Java, however, should not require a detailed understanding of the intricacies of the Java Memory Model. Instead, a set of high-level practices and guaran- tees should permit the programmer to write code that is both effi- cient and correct. We propose one possible set of rules in Section 4. We also give a set of rules to permit source-level reasoning about Java programs. Reordering constraints are critical to understanding any memory model. There is an important difference between the reordering constraints in a language-level memory model and in an architecture- level memory model. Architecture-level memory semantics are very concreteâthey describe the dynamic behavior of loads and stores on particular memory addresses. Instructions are reordered on the fly, and only when an instruction cannot be processed im- mediately. A programmer or a compiler, on the other hand, sees a static program where each variable may represent many different addresses dynamically. Furthermore, two different variables may both point to the same memory location (alias) during a particular program run. Optimizing compilers will reorder load operations, even when the variables referred to by those load operations may prove to alias at run time. A realistic memory model must permit such reordering. In the CRF model, instruction ordering is resolved dynamically, and is expressed compactly by a reordering table. For Java, the constraints on the order of memory operations must be expressible in terms of program variables. This permits the programmer to systematically juggle the order of operations in a Java program to obtain a program which makes a particular order of memory oper- ations evident. The algebraic rules we develop in Section 4.2 for- malize reordering constraints for Java at the source and bytecode levels. The detailed CRF semantics make it clear that the static reorderings are correct with respect to the permitted dynamic re-
Permission to make digital or hard copies of part or all of this work or personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or a fee.
OOPSLA â00, 10/00 Minneapolis, MN, USA Š 2000 ACM ISBN 1-58113-200-x/00/0010...$5.
orderings. They also show how to efficiently map the high-level model onto a modern processor architecture. This paper is the first detailed presentation of compilation us- ing CRF. We must enrich CRF by adding monitor-like locks and a freeze operation to capture the write-once semantics of final fields. Our semantics for final fields are of broad interest, as many sys- tems contain a large body of data which is written at most onceâ for example, object metadata in Java, or data structures in purely- functional programming languages such as Concurrent ML [14] or pH [2]. Java can be compiled efficiently by referring to the algebraic rules (for example while compiling source code to bytecode) or by using CRF operations directly (to represent memory operations during machine code generation). In either case, the compiler must reason statically about memoryâwhere the dynamic memory se- mantics require that two addresses be distinct, the compiler must require that the corresponding variables cannot alias. Many of the optimizations on modern programs rely on the use of a dependency graph. A graph with fewer edges gives the compiler more flexibil- ity in choosing instruction order, and frequently also reduces the algorithmic complexity of program analysis. The reordering tables we use yield straightforward dependency analysis algorithms for memory operations. The dynamic side conditions on reordering are captured statically by compiler analyses such as escape analy- sis, alias analysis, and pointer analysis. There are a number of different declarations which affect the vis- ibility of variables in different parts of a Java program. In this pa- per we address the behavior of the memory itself, and not issues of naming or scoping, so we do not distinguish between private, public, and package variables, nor between class (static) variables and instance variables. All of these obey the same basic underlying memory semantics. In the next section of this paper, we will examine some of the shortcomings of the present Java Memory Model. This gives a brief picture of the motivation behind the present work. In Sec- tion 3 we outline some related work on memory models both for programming languages and at the architectural level. Section 4 will be of particular interest to Java programmers wishing to learn how to write correct multithreaded programs. It presents a high- level overview of our memory model, and algebraic rules which describe operation reordering. The rules in this section can be de- rived from the more detailed semantics in the sections following. In Section 5 we present the operational semantics of CRF itself. Sec- tion 6 gives a translation from high-level Java memory operations into lower-level CRF operations. We conclude by discussing some of the issues we do not address in detail in the semantics.
2. PROBLEMS WITH THE CURRENT JAVA
MEMORY MODEL The memory model given in Chapter 17 of the Java Language Specification [8] has problems which fall into three broad cate- gories. First, it prohibits important compiler optimizations. Sec- ond, it is incomplete; no semantics are given for final fields, and the interaction of various kinds of storage is poorly specified. Finally, it is complex, and these complexities yield behavior that is difficult to capture or explain at the source level. The memory model we give in this paper is a response to these problems. Many potential memory semantics can be given for Java; in the course of develop- ing this paper, we have captured several such models within CRF. Thus, we view CRF as a general tool which avoids the problems we describe in this section.
2.1 Enabling compiler optimization The mapping from Java to CRF permits optimizations prohibited by the current Java Memory Model. The current model requires what Pugh refers to as coherence [13] (in all examples, memory cells are assumed to initially contain 0 or null, and no extraneous writes occur): Thread 1 Thread 2 v = p.f; w = q.f; x = p.f;
p.f = 2;
What if p == q at run time? Then in practice we have the follow- ing code: v = p.f; w = p.f; x = p.f; Coherence requires that if we observe w=2 then x=2. The com- piler is thus forbidden from performing fetch elimination and hav- ing x = v: v = p.f; w = q.f; x = v; Again, itâs vital that a memory model be able to reason about re- ordering all operationsâeven multiple loads from the same mem- ory location. The memory model we give in this paper permits loads to be re-ordered without recourse to alias analysis and as such always allows this optimization. This change reflects current prac- tice (reported as Bug #4242244 in Sunâs bug parade).
2.2 The semantics of final The current memory model for Java does not provide memory semantics for final. The semantics of final fields are captured in the CRF translation by using the Freeze operation to declare that a field will not change. However, keeping the contents of final locations themselves consistent isnât enough. The String Problem provides a remarkable case in point. Consider the following pared-down implementation of java.lang.String: public final class MyString { private final theCharacters; public MyString(char [] value) { char [] internalValue = value.clone(); theCharacters = internalValue; } ... } How do we guarantee that the call to value.clone() finishes all its writes before another thread looks at the contents of theChar- acters? This code may print a partial copy of the string a, whereas it ought to print all of it or throw a null pointer exception: Thread 1 Thread 2 char [] characters = âTâ,âaâ,ânâ,âgâ,â0â; a = new MyString(characters);
print(a);
A partially-initialized string is a big security problem when strings are used for naming internal state. Thread 1 should make sure internalValue is up to date before theCharacters may be read remotely, and Thread 2 must use the updated copy of theCharac- ters when it is printing. In the current model, we must synchro- nize every single access to the contents of theCharacters. This leads to unacceptable overhead, especially given the pervasiveness of strings used for internal naming. We instead give semantics which guarantee that the contents of theCharacters will be up to date as of initialization.
2nd LoadR StoreR LoadV StoreV LoadF StoreF Enter Exit EndCon 1st b b , w b b , w b b , w l l LoadR a a b no no StoreR a , v a b a b no no no LoadV a no no no no no StoreV a , v no no no no LoadF a a b StoreF a , v a b no Enter l no no no no no no Exit l no EndCon no no a b : Locations must never alias
Figure 2: Algebraic reordering table. Blank entries may always be reordered. Note that reordering tables are asymmetric; the first operation is found in the leftmost column, the second at the top of the table.
There are five aload and five astore bytecodes, one for references and one for each primitive type. All the array bytecodes include an array reference and an index as arguments. In this paper we will frequently refer to the address of a particu- lar field. This is not a language-level concept in Java! An address is a pairing of an object reference and either a field or an array index. Thus, for every address there is a clear notion of the object which contains the referenced field. At a high level there are three kinds of loads and stores in the Java language: LoadR and StoreR for regular locations, LoadV and StoreV for volatile locations, and LoadF and StoreF for final loca- tions. We choose this representation rather than using Java source code or byte code because we want to give rules which re-order memory operationsâconceptually quite simple, but complicated to describe if those memory operations involve manipulating a stack. Because Java uses monitor-style locking, we know that lock op- erations will be properly nested in the source program. Every syn- chronized region begins with an Enter and ends with an Exit of the corresponding monitor. We indicate monitors using an l. Our En- ter and Exit instructions correspond directly to the monitorenter and monitorexit bytecodes in Java. For the purposes of the memory model presented in this paper we add one additional operation, EndCon. The EndCon operation is used to indicate the end of a constructor method. As we shall see, this instruction is used to make sure the effects of object initializa- tion are visible to every thread. In order to share data between Java threads, it must be written to a field which is already shared by multiple threads. The class variables of all Java classes (fields notated as static) are always shared; in addition, new threads are created by creating an instance of a subclass of class java.lang.Thread, and this thread object will therefore be visible to the creating thread.
4.1 A discipline for Java programming
Any memory model for Java will dictate a programming disci- pline for the language. We therefore begin by outlining the pro- gramming discipline we are assuming from the Java programmer. Practices such as correct locking are already generally accepted (though widely disregarded). The other practices we propose are based on discussions on the Java Memory Model mailing list [9]. Other papers on memory semantics have attempted to give very precise requirements for programs, e.g. by defining a notion of properly synchronized programs [6, 1]. Such definitions prove re- markably slippery in practice. For example, the usual definition of properly synchronized programs refers to sequential consistency,
which requires the programmer to have a thorough and deep un- derstanding of two memory models in order to reason about pro- grams. Furthermore, our proposed model allows programmers to write code that certainly is not properly synchronized, yet is safe: we permit certain shared fields to be accessed without synchroniza- tion, and using volatile fields without synchronization leaves cor- rectness entirely up to the programmer. We therefore do not attempt to describe a precise set of condi- tions for correct program execution. Instead, we give guidelines for coding and guarantees we can make in return. It is possible (and sometimes desirable) to write deterministic code which operates outside these restrictions, but doing so requires detailed knowledge of the memory model. Operating within these requirements will yield well-behaved code.
Regular fields Operations on regular fields have no special ordering constraints, and thus must be used carefully. Regular loads and stores must be correctly synchronized. Threads must synchronize on a single shared object in order to ac- cess a regular shared field safely. No regular memory operation will escape from a synchronized region. It is unsafe to access a regular field without synchronization unless that field is not shared. Our semantics will yield a range of behaviors when an improperly synchronized program is run. Read-only objects can omit synchronization. We make a spe- cial exception to the need for synchronization for the regular fields of objects transitively reachable from a final field, and which are completely written before the reference is stored into the final field. This exception lets the programmer use information hiding to con- struct read-only versions of arbitrary structures which do not re- quire locking. For example, MyString acts somewhat like a read- only character array (by keeping theCharacters private); thus it does not require further synchronization.
Constructors and final fields Final fields allow the programmer to easily construct objects that can be read from multiple threads without locking. An object must not escape its constructor. No constructor function may make this visible to another thread. A creator method should be used instead if this behavior is desired. Any writes in a constructor will occur before other threads can see the object con- structed. Each constructor method is separately guarded, so if a subclass allows this to escape the superclass constructor will still behave in the expected way.
Final fields may be read without synchronization. It will be safe to access these locations without locking if the previous rule is obeyed. We ensure the data being read is current before the first final load from a particular address in a given thread.
Volatile fields
There are few restrictions on volatile fields, and they can be used by programmers to implement very free-form data exchange. Thus, using volatile storage is always comparatively dangerous. Any field may be made volatile without affecting program behavior. If the program was previously correct, changing the stor- age class of a variable to volatile does not change the behavior of the program. Thus, volatile fields obey the constraints of both reg- ular and final fields. Volatile loads and stores are sequentially consistent [10]. They may not be reordered in any way with respect to one another. Volatile stores fence previous memory operations. Memory operations which occur earlier in program order will be performed before a volatile store. Volatile loads fence subsequent memory operations. Memory operations which occur later in program order will be performed after a volatile load.
4.2 Algebraic rules
We present the model by first giving algebraic rules for Java memory operations, and then translating these operations into an enriched version of CRF. The algebraic rules will be derivable from the translation. Our goal is to permit the greatest possible num- ber of behaviors while preserving the programming discipline de- scribed above. Because reordering constraints are so vital to understanding any memory model, we begin by examining the reordering constraints for the Java Memory Model given in Figure 2. We can reorder instructions according to the table without resorting to complex reasoning about the CRF operations from which they are derived (Pughâs example, given in Section 2, shows such a high-level ap- proach is not possible in the current Java Memory Model). A lot of simple reasoning can happen at the algebraic level; in many cases we can get a picture of how threads will interact simply by reorder- ing the instructions of threads according to the table, then seeing how those instructions interleave. The condition a b captures the usual constraints between oper- ations on a single memory address. Note that loads on the same address may be reordered freely. The ânoâ constraints for volatile memory operations capture the sequentially consistent behavior and fence semantics of volatile memory (the operations must occur in program order). The ânoâ constraints between memory operations and lock operations prevent memory operations from escaping a lock region. Note that final fields should only be written before the object is visible to other threads; consequently, lock regions and volatile memory operations do not affect the ordering of final memory operations. Note also that we allow arbitrary loads and stores to move into a lock region.
4.3 Eliminating operations
We can eliminate certain operations if doing so is consistent with some execution of a thread. This will reduce the possible pro- gram behaviors, but will not introduce any new behavior. Thus, the correctness of operation elimination at this high level depends on showing similar eliminations can be performed within CRF it- self. We may eliminate any load operation if our reordering rules allow it to be preceded immediately by a load or store to the same address. Similarly, we may eliminate any store which can be re-
ordered so that it is immediately followed by a second store to the same address. For final loads, we allow fetch elimination if a load or store to the same address occurs anywhere earlier in the program order.
4.4 Compilation using algebraic rules A static, purely local notion of how memory operations behave within a thread is indispensable for generating efficient code with- out resorting to complex inter-thread analyses. Optimizations in- volving code motion require the construction of a dependency graph. Our goal is to create a dependency graph with as few edges as pos- sible, giving the compiler the greatest possible leeway to reorder instructions. Constructing a dependency graph using the reordering table is simple. For every pair of operations A and B , where A occurs be- fore B in the program, we see if our reordering table permits A ; B to be reordered to B ; A. If it does, no dependency exists between the instructions. If they cannot be reordered, we add a dependency edge from A to B. The resulting graph is unique modulo transitiv- ity. In practice, of course, we can be more careful and avoid adding transitive edges to the graph (these edges increase algorithmic com- plexity without changing results). While this dependency graph must be conservative, since not all information is known at compile time, our side conditions corre- spond to well-known compiler analyses: Type information and alias analysis can approximate the con- dition a b. Distinct fields and disjoint types will never share an address. Alias analysis can show that many remaining addresses are certainly different. Points-to analyses can determine which loads and stores might potentially refer to or be referred to by a particular final field, ap- proximating the condition a B which we will encounter in the CRF semantics. Note that type information can be used to give a conservative approximation to points-to analysis. Inter-thread escape analysis [4, 19] will reveal when an object is used entirely within one thread. In this case, we can eliminate coherency operations on the object. Local loads and stores can therefore be reordered freely. Only the constraint a b holds for purely local fields.
4.5 Other constraints on reordering We have noted already that a compiler must reason about pro- gram addresses symbolically, whereas a running JVM can work with actual addresses. In addition, however, a compiler must work with unresolved control flowâconditionals whose outcome cannot be determined at compile time. We do not consider control flow to constrain instruction reordering, except that the results of reorder- ing must be consistent with an execution of the original program (for example, data dependency must be respected). Consider the following example:
Thread 1 Thread 2 if (p.next == p) List tmp = p.next; system.out.print("y"); if (tmp.next == null) system.out.print("es");
p.next = p;
The data dependency between tmp and tmp.next ensures that the latter read must occur after the former read. It is therefore impos- sible for the program to print âyesâ. It may, however, print âyâ and throw a null pointer exceptionâthe initialization of tmp can occur
Local Rules
( r = Storel a , v ; instructions , completions , cache a : ) ( instructions , r / completions , cache a : v Dirty )
( r = Loadl a ; instructions , completions , cache a : v s ) ( instructions , r v / completions , cache a : v s )
( r = Commit a ; instructions , completions , cache ) where a is not in cache , or a is Clean ( instructions , r / completions , cache )
( r = Reconcile a ; instructions , completions , cache ) where a is not in cache , or a is Dirty or Frozen ( instructions , r / completions , cache )
( r = Fence a , b ; instructions , completions , cache ) ( instructions , r / completions , cache )
( r = Freeze a ; instructions , completions , cache a : v Clean ) ( instructions , r / completions , cache a : v Frozen )
( r = Freeze a ; instructions , completions , cache ) ( instructions , r / completions , cache )
Background Rules
( instructions , completions , cache a : v s ) where s is Clean or Frozen ( instructions , completions , cache )
( instructions , completions , cache ) / threads , memory a : v where cache contains no mapping for a ( instructions , completions , cache a : v Clean ) / threads , memory a : v
( instructions , completions , cache a : v Dirty ) / threads , memory a : ( instructions , completions , cache a : v Clean ) / threads , memory a : v
Figure 4: Rewrite rules for basic CRF
Local Rules
( r = Lock l ; instructions , completions , cache l : n Locked ) ( instructions , r n / completions , cache l : n 1 Locked )
( r = Unlock l ; instructions , completions , cache l : n 1 Locked ) ( instructions , r n / completions , cache l : n Locked )
Background Rules
( instructions , completions , cache ) / threads , memory l : 0 where cache contains no mapping for l ( instructions , completions , cache l : 0 Locked ) / threads , memory
( instructions , completions , cache l : 0 Locked ) / threads , memory ( instructions , completions , cache ) / threads , memory l : 0
Figure 5: Additional rewrite rules for CRF augmented with locking
2nd Loadl Storel Lock Unlock Freeze Commit Reconcile Fencer Fencew 1st b b b b b b b B , B , Loadl a a b a B Storel a a b a b a b Lock a a b a B a B Unlock a a B a B Freeze a Commit a a b a B Reconcile a a b a b Fence (^) r , A b A b A b A Fence (^) w , A b A b A b A a b : Addresses must not match a B : Address of 1st instr must not be contained in pre-address of fence b A : Address of 2nd instr must not be contained in post-address of fence : Either r (read) or w (write)
Figure 6: Reordering table for extended CRF (Blank entries may always be reordered).
The remaining rules move data between a thread and main mem- ory, and thus act on the state of the entire system (which includes the remaining threads, though they are not affected by the opera- tions). A thread can at any time cache an entry contained in global memory if it has not done so already, or can write dirty data back to main memory. Again, instruction execution happens purely lo- cally within a threadâthe state of main memory is required only for background operations. Thus, we can take the pair of load and store defined earlier and execute them locally, on a single processor:
( r 1 = Storel a , 5; r 2 = Loadl a ; instrs , c , cache a : 0 Clean )
( r 2 = Loadl a ; instrs , r 1 = / c , cache a : 5 Dirty )
( instrs , r 2 = 5 / r 1 = / c , cache a : 5 Dirty )
Thus, we remove instructions one at a time from the instruction stream, and keep track of their results and of the contents of the cache. To ensure that background operations complete, we use the thread- level operations Commit and Reconcile. Commit ensures the re- sults of a write to a particular location reach main memory. Recon- cile ensures that the cache is refreshed with new data for a particular location before it is read. These behaviors are reflected in different reordering rules for Commit and Reconcile. Note that these instruc- tions simply block and wait for the background rules to do the real work of moving data between cache and memory. Picking up from the previous example, the next instruction might be a Commit, in which case we must wait for a to be written back to memory:
( r = Commit a ; instrs , c , cache a : 5 Dirty ) / threads , memory [ a := 0]
( r = Commit a ; instrs , c , cache a : 5 Clean ) / threads , memory [ a := 5]
( instrs , r = / c , cache a : 5 Dirty ) / threads , memory [ a := 5]
Real systems use much more sophisticated cache coherence pro- tocols, and in practice these operations will not oblige a processor either to suspend or to flush entries from its cache (as we shall see in Section 5.5, Commit and Reconcile are no-ops on most modern architectures).
For final fields we will need some way to declare that a loca- tionâs value should remain invariant. We thus add a Frozen cache state, which declares that a memory location can remain in the cache indefinitely. A Freeze operation optionally marks a cache line as Frozen (it may instead be ignored; this decision is non- deterministic). Frozen cache lines need not be subjected to back- ground operations.
5.2 Augmented CRF for Java We can imagine performing locking in CRF using some varia- tion on Dekkerâs algorithm. In practice, actual architectures pro- vide more efficient atomic memory primitives. Augmenting CRF with monitor-style synchronization makes our semantics simpler and clearer. These augmentations are described in Figure 5. Lock and Unlock are the only atomic memory operations, and as such require Locked access to their address (and corresponding back- ground operations). Note that in our semantics a Locked location is removed from main memory; in practice we would use lower-level atomic mem- ory primitives to check for a distinguished value. Monitors can be locked recursively; thus locks contain a count of the number of times the owning thread has locked the lock. Note also that lock- ing does nothing to enforce mutual exclusion; it just manipulates a lock. We rely on explicit Fence operations (described in the next section) to define synchronization regions. Finally, Java associates a unique lock location with each object in the system; because these lock locations are not regular fields, they will only be accessed us- ing Lock and Unlock. We therefore give no semantics for reading and writing locked locations.
5.3 Reordering Much of the power of the CRF model comes from the ability to reorder instructions. For our purposes this reordering captures a mix of both compiler optimizations and architectural speculation and reordering. In practice, the greatest constraint on re-ordering is data dependence: operation ordering must respect data depen- dencies. We make use of data dependence constraints in our se- mantics. Fine-grained Fence instructions enforce ordering between operations which are not data-dependent. Each memory fence has a pair of arguments, a pre-address and a post-address, and imposes an ordering constraint between mem- ory operations involving the pre- and post- addresses. For example, Fencerw a , b prevents preceding reads on address a from being re-
Operation Regular Final Volatile Store a , v ; Storel a , v ; Commit a ;
Storel a , v ; Commit a ; Freeze a ;
Fencerw (^) VR , a ; Fenceww VR , a ; Storel a , v ; Commit a ; v = Load a ; Reconcile a ; v = Loadl a ;
Reconcile a ; v = Loadl a ; Freeze a ;
Fencewr V, a ; Reconcile a ; v = Loadl a ; Fencerr a , (^) VR ; Fencewr a , (^) R;
Figure 7: CRF translations for Java loads and stores
A precise translation of these instructions into dynamic CRF would require either precise type information for each memory location, or a giant loop over all of memory. As noted above, however, a compiler is free to choose a less permissive translation of these operations (for example, by substituting global memory fences for finer-grained Fence operations). We expect compilers to exploit our reordering rules so that many fences may be consoli- dated.
6.1 Regular memory
CRFâs fine-grained memory operations nicely express the se- mantics of regular memory locations, which ordinarily require lock- ing for coherence (first column of Figure 7). We Fence both volatile and regular locations during locking (Figure 8) so that we can safely change a regular location into a volatile location without changing the behavior of a program. Note that our semantics permit any load or store operation to be moved into a lock region. Thus, a lock region simply prevents memory operations inside the region from being moved outside. We synchronize on all lock locations before we enter a lock region; this guarantees that previous exit operations complete before en- try. This condition is necessary to prevent the memory model from introducing deadlocks.
6.2 Final fields
The semantics of final fields (second column of Figure 7) require explanation. We must ensure every final field is up to date when a constructor completes. This is the purpose of the EndCon opera- tion, which is the only operation in our semantics that affects the ordering of operations on final fields. Objects pointed to by a final field are up to date if theyâve been fully initialized by the end of the constructor, since the fence in EndCon ensures those initializ- ing writes are complete as well. When we follow a reference from a final field, we cannot Reconcile until we have fetched the object reference from the final field. Consequently data dependence is sufficient to enforce the correct semantics for final references. If we did not ensure final writes were completed in the construc- tor, we would need to make sure they were complete before a ref- erence to the containing object escaped. We would then need to translate Store as follows (with a concomitant change for StoreF):
Store a , p ;
Fenceww p , a ; Storel a , p ; Commit a ;
Here the notation p indicates all memory locations in the object referred to by pointer p. This fence would only affect dependent writes, but it requires a Fence before every Store. Note the effect of Freeze a when p 1 = LoadF a is followed by p 2 = LoadF a and we move the Freeze a as far down in instruction
Operation Translation Enter l ; Fenceww (^) L, l ; Lock l ; Fencewr l , (^) VR ; Fenceww l , (^) VRL ; Exit l ; Fenceww VR , l ; Fencerw VR , l ; Unlock l ; EndCon; Fenceww , (^) VR ;
Figure 8: CRF translations for Java synchronization opera- tions
order as possible, eliminating Reconcile a :
Reconcile a ; p 1 = Loadl a ; Freeze a ; Reconcile a ; p 2 = Loadl a ; Freeze a ;
Reconcile a ; p 1 = Loadl a ; p 2 = Loadl a ; Freeze a ; Freeze a ;
Reconcile a ; p 1 = Loadl a ; Freeze a ; p 2 = p 1 ;
Replacing p 2 = Loadl a by p 2 = p 1 in the above yields a legal be- havior, and thus LoadF operations can be combined. The remain- ing redundant operations then combine trivially. Similarly, when we follow StoreF a , p 1 by p 2 = LoadF a :
Storel a , p 1 ; Commit a ; Freeze a ; Reconcile a ; p 2 = Loadl a ; Freeze a ;
Storel a , p 1 ; p 2 = Loadl a ; Commit a ; Freeze a ; Freeze a ;
Storel a , p 1 ; Commit a ; Freeze a ; p 2 = p 1 ;
Again, we know that we can fetch-eliminate p 2 = Loadl a. Once again we have fetch-eliminated the LoadF.
6.3 Volatile memory Operations on volatile fields (third column of Figure 7) cannot be reordered at all. This is quite easy to capture by adding fences before every volatile memory operation separating it from other volatile operations. Every volatile read must be followed by two fences to enforce acquire semantics; fences before every volatile write enforce release semantics. Note that as with locking these fences do not affect final locations. The guarantees given by End- Con are sufficient for this purpose, as long as we make sure an ob- ject reference does not escape from the constructor. Because End- Con fences volatile writes as well as final writes, we can correctly replace final fields with volatile fields.
6.4 Synchronization The translations for Enter and Exit (Figure 8) must provide the necessary synchronization to enforce the ordering constraints re- quired by monitors. A pair of fence operations after the Lock in Enter and before the Unlock in Exit prevent loads and stores from escaping the synchronized region. However, we must still ensure that Exit operations can be reordered, but that they are not reordered with respect to Enter operations. As a result, we do not fence lock locations in the translation for Exit, but we fence them both before and after every Enter operation (thus preventing Exit from being reordered with respect to Enter in either direction). As a matter of convention, we use only a write fence to constrain the ordering of lock locations in the translation.
The translation of EndCon is quite straightforwardâit simply constrains preceding writes to occur before succeeding non-final writes. This results in a single Fence instruction as shown in Fig- ure 8.
6.5 Allowing lock elimination
The translation in the previous section was simplified to make the presentation clearer. It does not allow for the elimination of synchronization when the data involved is local to one processorâ even if we eliminate the Lock and Unlock operations, we must sim- ulate the effect of the Fence instructions which accompany them. Experiments show that static elimination of useless locking can re- duce synchronization by approximately 50% [4]. We can eliminate useless lock operations when they are nested with more useful ones. This is because we may enlarge a lock region as long as we donât change the nesting of locks. Consider this example:
... synchronized(o) { o.m1(); synchronized(p) { p.m2(o); } o.m3(); } ...
If neither m1 nor m3 performs synchronization, we can actually en- large the region p to overlap with region o :
... synchronized(o) { synchronized(p) { o.m1(); p.m2(o); o.m3(); } } ...
In practice we usually want to make synchronization regions as small as possible, but consider the effect of this transformation if p is not shared: we perform the same Fence operations in quick succession on entry and exit, and we will not be able to tell if p is actually locked or not. Thus, we may erase synchronized(p) with no effect. We are therefore really worried about eliminating useless syn- chronization that is not nicely nested. Imagine none of the method calls in the following code contains synchronization:
... synchronized(o) { o.m1(); } synchronized(p) { p.m2(); } p.m3(); ...
In this case, if p is not shared we must still fence the synchroniza- tion region for p. This means the call to m2 may not be moved. It is not hard to modify our translation to permit further elimina- tion of redundant locks. There is no need for a Fence unless new information is being obtainedâthat is, unless some other thread has synchronized on the object and modified it in some way. We imagine that the Lock operation returns the identity of the previous thread to hold the lock. We fence only when some other thread
Operation Translation Enter l ; Fenceww (^) L, l ; r = Lock l ; if ( r != currentThread ) Fencewr l , (^) VR ; Fenceww l , (^) VRL ;
Figure 9: Improved CRF translation for Enter
has used the lock. The operation Enter l is therefore translated as shown in Figure 9. Now we eliminate lock operations by âdrifting downâ. Opera- tions escape from the top of the synchronization region, where the Fence operations are skipped:
... synchronized(o) { o.m1(); } p.m2(); p.m3(); synchronized(p) { } ...
There is one asymmetry here: the eliminated synchronization regions will get stuck when they reach a synchronization region that actually exists:
... p.m2(); p.m3(); synchronized(p) { } synchronized(o) { o.m1(); } ...
This prevents prior code (in this case the invocations of m2 and m3) from being moved into the synchronization region for no particu- larly good reason. This restriction is necessary because our new translation gives equal treatment to locks which are never shared and locks which simply are not shared yet. If p later becomes shared, such code motion would lead to incorrectness or deadlock. This is a shortcoming of the dynamic nature of our semantics.
7. CONCLUSION We have simplified our presentation of the Java Memory Model. Other translations yielding the same model as described here are possibleâfor example, by doing pairwise instruction translation we can use single-address Fence operations in our translation of LoadV and StoreV. Moreover, the memory model we present is not the only possible memory model for Java. We have used the CRF framework to explore a series of different proposals for a Java Memory Model in order to assess their effects on compilation. More permissive memory models exist which use data-dependent synchronization; they are, however, arguably more difficult for the programmer to understand. Javaâs strongly-ordered exception model has a major influence on compiled code; in many cases null pointer checks will require otherwise unconstrained memory operations to be ordered. Our choice of memory model does not affect this decision. We must simply respect these additional constraints on operation order.