Docsity

Concurrent Programming with Java: Thread Locals and Object Isolation, Study notes of Programming Languages

Toggle sidebar
bg1
USENIX COOTS '98 April 27, 1998
Designing Concurrent Object-Oriented Programs
in Java 1
© 2003 David Holmes and Doug Lea 1
Introduction to Concurrent
Programming in Java™
(lots of slides cut for 433)
David Holmes
DLTeCH Pty Ltd
Brisbane, Australia
Doug Lea
State University
of New York
Oswego, NY
dl@cs.oswego.edu
http://gee.cs.oswego.edu/~dl/
© 2003 David Holmes and Doug Lea 2
Designing Objects for Concurrency
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Concurrent Programming with Java: Thread Locals and Object Isolation and more Study notes Programming Languages in PDF only on Docsity!

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 1

Introduction to Concurrent

Programming in Java™

(lots of slides cut for 433)

David Holmes

DLTeCH Pty Ltd

Brisbane, Australia

[email protected]

Doug Lea

State University

of New York

Oswego, NY

[email protected]

http://gee.cs.oswego.edu/~dl/

© 2003 David Holmes and Doug Lea 2

Designing Objects for Concurrency

IsolationAvoiding interference by not sharingImmutabilityAvoiding interference by avoiding changeLockingDynamically guaranteeing exclusive accessSplitting objectsChanging representation to facilitate concurrency controlContainmentGuaranteeing exclusive control of internal componentsManaging ownershipProtecting unhidden componentsAlternatives to synchronizationvolatiles and the Java Memory Model

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 3 IsolationObjects that are not shared can not suffer interferenceHeap objects accessible only from current threadParameters and local variablesApplies to references not the objects referred to  java.lang.ThreadLocal  Simplifies access from other objects running in same threadNo need for any synchronizationObjects can be shared across threads provided they are isolated to one thread at a timeTransfer of ownership protocolsT1 uses O1, hands off to T2 and then forgets about OTransfer requires synchronization—subsequent use of object does not © 2003 David Holmes and Doug Lea 4 Thread LocalsSuppose you want multiple web servers, each running in a different thread, and each using a different document directoryCould define a documentRoot field in WebServer classOr, 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 objectsNo need to define subclasses or control thread creationAll methods running in the thread can access when needed  ThreadLocal s are often package accessible statisticsNo 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(); // ... }

Designing Concurrent Object-Oriented Programs

© 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 initialisationStill no safety or liveness concernsNo interference as per-instance state never changesJava blank final s enforce most senses of immutabilityImmutability 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 ObjectsSuppose 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 sharedCan 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

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 9 ContainmentStrict containment creates islands of objectsApplies recursivelyAllows inner code to run fasterCan be used with legacy sequential codeRequires inner code to be communication closedNo unprotected calls into or out of islandRequires outer objects to never leak inner referencesOr uses ownership transfer protocolCan be difficult to enforce and check © 2003 David Holmes and Doug Lea 10 Hierarchical Containment LockingApplies when logically contained parts are not hidden from clientsAvoids deadlocks that could occur if parts fully synchronisedAll parts use lock provided by the common ownerCan use either internal or external conventions

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 13 Subclassing Unsafe CodeSuppose processRequest invokes handlerHelper.mountFileSystem(); where: class HandlerHelper{ native void mountFileSystem(); }  If we don’t trust this class to be thread-safe, we couldWrap calls in synch blocks (I.e., containment), orCreate a simple subclass that adds synch… class SafeHandlerHelper extends HandlerHelper{ synchronized void mountFileSystem() { super.mountFileSystem(); } } … and instantiate it insteadThis localizes synch control in the place it is neededSubclassing is usually the most convenient way to do thisCan also use unrelated wrapper classes and delegateCan generalize to “template method”schemes (discussed later) © 2003 David Holmes and Doug Lea 14 State Dependent ActionsState DependenceBalkingGuarded SuspensionOptimistic RetriesSpecifying Policies

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 15 Examples of State Dependent ActionsOperations on collections, streams, databasesRemove an element from an empty queueAdd an element to a full bufferOperations on objects maintaining constrained valuesWithdraw money from an empty bank accountOperations requiring resourcesPrint a fileOperations requiring particular message orderingsRead an unopened fileOperations on external controllersShift to reverse gear in a moving car © 2003 David Holmes and Doug Lea 16 Policies for State Dependent ActionsSome Policy choices for dealing with pre-and post-conditions

Designing Concurrent Object-Oriented Programs

© 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 GuardingCheck state upon entryIf not in right state, waitSome other action in some other thread may eventually cause a state change that enables resumptionIntroduces liveness concernsRelies on actions of other threads to make progressUseless in sequential programsClient must ensure correct state before callingGeneralisation of locking for state dependent actionsLocked: Wait until ready (not engaged in other methods)Guarded: Wait until an arbitrary state predicate holds

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 21 Guarding MechanismsBusy-waitsThread continually spins until a condition holds while (!condition) ; // spin // use condition  Requires multiple CPU’s or timeslicingNo way to determine this until JDK 1. int nCPUs = Runtime.availableProcessors();  But busy waiting can sometimes be useful; generally when

 The conditions latch—once set true, they never become false

SuspensionThread stops execution until notified that the condition may be trueSupported in Java via wait-sets and locks © 2003 David Holmes and Doug Lea 22 Guarding Via SuspensionWaiting 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 loopChange of state may not be what you needCondition may have changed againNo built-in protection from ‘barging’Break the rule only after you have proven it is safe to do so

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 25 Wait-sets and Notifications (cont…)Consider notify() as an optimization which can only be usedWhen only one thread can benefit from the change of state, andAll threads are waiting for the same change of stateOr else another notify() is done by the released threadAnd these conditions will also hold in all subclassesConditional notification is another optimizationWhen you know what state changes are being waited uponSubclasses may invalidate your ‘knowledge’Use of wait() , notifyAll() and notify() similar toCondition queues of classic MonitorsCondition variables of POSIX PThreads APIBut only one ‘queue’ per objectGreat 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; } }

Designing Concurrent Object-Oriented Programs

© 2003 David Holmes and Doug Lea 27 TimeoutsIntermediate points between balking and guardingCan vary timeout parameter from zero to infinityUseful for heuristic detection of failuresDeadlocks, crashes I/O problems, network disconnectsBut cannot be used for high-precision timing or deadlinesTime can elapse between wait and thread resumptionTime can elapse after checking the time!Java implementation constraints  wait(ms) does not automatically tell you if it returns because of notification vs timeoutMust check for both. Order and style of checking can matter, depending onIf always OK to proceed when condition holdsIf timeouts signify errorsNo 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(); }