








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!









© 2003 David Holmes and Doug Lea 1
(lots of slides cut for 433)
© 2003 David Holmes and Doug Lea 2
Isolation Avoiding interference by not sharing Immutability Avoiding interference by avoiding change Locking Dynamically guaranteeing exclusive access Splitting objects Changing representation to facilitate concurrency control Containment Guaranteeing exclusive control of internal components Managing ownership Protecting unhidden components Alternatives to synchronization volatiles and the Java Memory Model
© 2003 David Holmes and Doug Lea 3 Isolation Objects that are not shared can not suffer interference Heap objects accessible only from current thread Parameters and local variables Applies to references not the objects referred to java.lang.ThreadLocal Simplifies access from other objects running in same thread No need for any synchronization Objects can be shared across threads provided they are isolated to one thread at a time Transfer of ownership protocols T1 uses O1, hands off to T2 and then forgets about O Transfer requires synchronization—subsequent use of object does not © 2003 David Holmes and Doug Lea 4 Thread Locals Suppose you want multiple web servers, each running in a different thread, and each using a different document directory Could define a documentRoot field in WebServer class Or, define the document root as a variable tied to the Thread Easiest way to do this is to use java.lang.ThreadLocal Equivalent to adding instance variables to all Thread objects No need to define subclasses or control thread creation All methods running in the thread can access when needed ThreadLocal s are often package accessible statistics No interference when ALL access is within same thread public class WebServer { static final ThreadLocal documentRoot = new ThreadLocal(); // ... public WebServer(int port, File root) throws IOException { // ... documentRoot.set(root); } private void processRequest(Socket sock)throws IOException File root = (File) documentRoot.get(); // ... }
© 2003 David Holmes and Doug Lea 7 Immutable Objects class ImmutableAdder { private final int offset; // blank final ImmutableAdder(int offset) { this.offset = offset; } int add(int i) { return i + offset; } } Object state frozen upon initialisation Still no safety or liveness concerns No interference as per-instance state never changes Java blank final s enforce most senses of immutability Immutability is often suitable for closed Abstract Data Types eg. java.lang.String , java.lang.Integer © 2003 David Holmes and Doug Lea 8 Containment of Unsafe Objects Suppose Statistics class was written as follows: public static class Statistics { // Mutable! public long requests; public double avgTime; public Statistics(long requests, double avgTime) { this.requests = requests; this.avgTime = avgTime; } } Fields are public and mutable! Therefore instances can not be shared Can be safely contained within a WebServer instance private final Statistics stats = new Statistics(0,0.0); public synchronized Statistics getStatistics() { return new Statistics(stats.requests, stats.avgTime); } private void processRequest(Socket sock) throws IOException { // .... synchronized(this) { double total = stats.avgTime*stats.requests + elapsed; stats.avgTime = total / (++stats.requests); } } Can’t expose mutable state so we make copies of it
© 2003 David Holmes and Doug Lea 9 Containment Strict containment creates islands of objects Applies recursively Allows inner code to run faster Can be used with legacy sequential code Requires inner code to be communication closed No unprotected calls into or out of island Requires outer objects to never leak inner references Or uses ownership transfer protocol Can be difficult to enforce and check © 2003 David Holmes and Doug Lea 10 Hierarchical Containment Locking Applies when logically contained parts are not hidden from clients Avoids deadlocks that could occur if parts fully synchronised All parts use lock provided by the common owner Can use either internal or external conventions
© 2003 David Holmes and Doug Lea 13 Subclassing Unsafe Code Suppose processRequest invokes handlerHelper.mountFileSystem(); where: class HandlerHelper{ native void mountFileSystem(); } If we don’t trust this class to be thread-safe, we could Wrap calls in synch blocks (I.e., containment), or Create a simple subclass that adds synch… class SafeHandlerHelper extends HandlerHelper{ synchronized void mountFileSystem() { super.mountFileSystem(); } } … and instantiate it instead This localizes synch control in the place it is needed Subclassing is usually the most convenient way to do this Can also use unrelated wrapper classes and delegate Can generalize to “template method”schemes (discussed later) © 2003 David Holmes and Doug Lea 14 State Dependent Actions State Dependence Balking Guarded Suspension Optimistic Retries Specifying Policies
© 2003 David Holmes and Doug Lea 15 Examples of State Dependent Actions Operations on collections, streams, databases Remove an element from an empty queue Add an element to a full buffer Operations on objects maintaining constrained values Withdraw money from an empty bank account Operations requiring resources Print a file Operations requiring particular message orderings Read an unopened file Operations on external controllers Shift to reverse gear in a moving car © 2003 David Holmes and Doug Lea 16 Policies for State Dependent Actions Some Policy choices for dealing with pre-and post-conditions
© 2003 David Holmes and Doug Lea 19 Example: Balking Bounded Buffer public class BalkingBoundedBuffer implements Buffer { private List data; private final int capacity; public BalkingBoundedBuffer(int capacity) { data = new ArrayList(capacity); this.capacity = capacity; } public synchronized Object take() throws Failure { if (data.size() == 0) throw new Failure("Buffer empty"); Object temp = data.get(0); data.remove(0); return temp; } public synchronized void put(Object obj) throws Failure { if (data.size() == capacity) throw new Failure("Buffer full"); data.add(obj); } public synchronized int size() { return data.size();} public int capacity() {return capacity;} } © 2003 David Holmes and Doug Lea 20 Guarding Check state upon entry If not in right state, wait Some other action in some other thread may eventually cause a state change that enables resumption Introduces liveness concerns Relies on actions of other threads to make progress Useless in sequential programs Client must ensure correct state before calling Generalisation of locking for state dependent actions Locked: Wait until ready (not engaged in other methods) Guarded: Wait until an arbitrary state predicate holds
© 2003 David Holmes and Doug Lea 21 Guarding Mechanisms Busy-waits Thread continually spins until a condition holds while (!condition) ; // spin // use condition Requires multiple CPU’s or timeslicing No way to determine this until JDK 1. int nCPUs = Runtime.availableProcessors(); But busy waiting can sometimes be useful; generally when
Suspension Thread stops execution until notified that the condition may be true Supported in Java via wait-sets and locks © 2003 David Holmes and Doug Lea 22 Guarding Via Suspension Waiting for a condition to hold: synchronized (obj) { while (!condition) { try { obj.wait(); } catch (InterruptedException ex) { ... } } // make use of condition } Changing a condition: synchronized (obj) { condition = true; obj.notifyAll(); // or obj.notify() } Golden rule: Always test a condition in a loop Change of state may not be what you need Condition may have changed again No built-in protection from ‘barging’ Break the rule only after you have proven it is safe to do so
© 2003 David Holmes and Doug Lea 25 Wait-sets and Notifications (cont…) Consider notify() as an optimization which can only be used When only one thread can benefit from the change of state, and All threads are waiting for the same change of state Or else another notify() is done by the released thread And these conditions will also hold in all subclasses Conditional notification is another optimization When you know what state changes are being waited upon Subclasses may invalidate your ‘knowledge’ Use of wait() , notifyAll() and notify() similar to Condition queues of classic Monitors Condition variables of POSIX PThreads API But only one ‘queue’ per object Great complicates some designs and easily leads to ‘nested monitor lockouts’ Any Java object can be used just for its wait-set and/or lock © 2003 David Holmes and Doug Lea 26 Example: Guarded Bounded Buffer public class GuardedBoundedBuffer implements Buffer { private List data; private final int capacity; public GuardedBoundedBuffer(int capacity) { data = new ArrayList(capacity); this.capacity = capacity; } public synchronized Object take() throws Failure { while (data.size() == 0) try { wait(); } catch(InterruptedException ex) {throw new Failure();} Object temp = data.get(0); data.remove(0); notifyAll(); return temp; } public synchronized void put(Object obj) throws Failure { while (data.size() == capacity) try { wait(); } catch(InterruptedException ex) {throw new Failure();} data.add(obj); notifyAll(); } public synchronized int size() { return data.size(); } public int capacity() { return capacity; } }
© 2003 David Holmes and Doug Lea 27 Timeouts Intermediate points between balking and guarding Can vary timeout parameter from zero to infinity Useful for heuristic detection of failures Deadlocks, crashes I/O problems, network disconnects But cannot be used for high-precision timing or deadlines Time can elapse between wait and thread resumption Time can elapse after checking the time! Java implementation constraints wait(ms) does not automatically tell you if it returns because of notification vs timeout Must check for both. Order and style of checking can matter, depending on If always OK to proceed when condition holds If timeouts signify errors No way to establish with 100% certainty that timeout occurred © 2003 David Holmes and Doug Lea 28 Timeout Example public synchronized void put(Object obj, long timeout) throws Failure { if (timeout <= 0) // disallowing zero avoids semantic problems throw new IllegalArgumentException("timeout must be > 0"); long timeleft = timeout; long start = System.currentTimeMillis(); while (data.size() == capacity) { try { wait(timeleft); } catch(InterruptedException ex) { throw new Failure(); } // notified, timed-out or spurious? if (data.size() < capacity) break; // condition holds - don't care if we timed out else { // maybe a timeout long elapsed = System.currentTimeMillis() - start; timeleft = timeout - elapsed; if (timeleft <= 0) throw new Failure("Timed-out"); } // spurious so wait again } data.add(obj); notifyAll(); }