DOC PREVIEW
UMD CMSC 433 - Designing Objects for Concurrency

This preview shows page 1-2 out of 5 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

USENIX COOTS '98April 27, 1998Designing Concurrent Object-Oriented Programs in Java1© 2003 David Holmes and Doug Lea48Designing Objects for ConcurrencyIsolationAvoiding interference by not sharingImmutabilityAvoiding interference by avoiding changeLockingDynamically guaranteeing exclusive accessSplitting objectsChanging representation to facilitate concurrency controlContainmentGuaranteeing exclusive control of internal componentsManaging ownership Protecting unhidden componentsAlternatives to synchronizationvolatiles and the Java Memory Model© 2003 David Holmes and Doug Lea49IsolationObjects that are not shared can not suffer interferenceHeap objects accessible only from current threadParameters and local variablesApplies to references not the objects referred tojava.lang.ThreadLocalSimplifies 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 O1Transfer requires synchronizationsubsequent use of object does not© 2003 David Holmes and Doug Lea50Thread LocalsSuppose you want multiple web servers, each running in a different thread, and each using a different document directoryCould define a documentRootfield in WebServerclassOr, define the document root as a variable tied to the ThreadEasiest way to do this is to use java.lang.ThreadLocalEquivalent to adding instance variables to all ThreadobjectsNo need to define subclasses or control thread creationAll methods running in the thread can access when neededThreadLocalsare often package accessible statisticsNo interference when ALL access is within same threadpublic class WebServer{static final ThreadLocaldocumentRoot = new ThreadLocal();// ...public WebServer(intport, File root) throws IOException{// ...documentRoot.set(root);}private void processRequest(Socket sock)throws IOExceptionFile root = (File) documentRoot.get();// ...}© 2003 David Holmes and Doug Lea51When to Use Thread LocalsVariables that apply per-activity, not per-objectTimeout values, transaction IDs, Principals, current directories,default parametersReplacements for static variablesWhen different threads should use different valuesTools to eliminate need for lockingUsed internally in JVMs to optimize memory allocation, locks, etc via per-thread caches© 2003 David Holmes and Doug Lea52Stateless Objectsclass StatelessAdder{int addOne( inti) { return i + 1; }int addTwo( inti) { return i + 2; }}There are no special concurrency concernsNo storage conflicts as no per-instance stateNo representation invariants as no representationMultiple concurrent executionsso no liveness problemsNo need to create threads to make this call No interaction with other objectsso no concurrent protocol design issuesExample: java.lang.Math© 2003 David Holmes and Doug Lea75State Dependent ActionsState DependenceBalkingGuarded SuspensionOptimistic RetriesSpecifying PoliciesUSENIX COOTS '98April 27, 1998Designing Concurrent Object-Oriented Programs in Java2© 2003 David Holmes and Doug Lea76State DependenceTwo aspects of action control:A messagefrom a clientThe internal stateof the hostDesign Steps:Choose policiesfor dealing with actions that can succeed only if object is in particular logical stateDesign interfacesand protocolsto reflect policyEnsure objects able to assessstate to implement policypolicy controlanAction{ }state, acquaintancesmessageThere is not a separate accept mechanism in Java. So must implement policies in action methods themselves.accept© 2003 David Holmes and Doug Lea77Examples 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 Lea78Policies for State Dependent ActionsSome Policy choices for dealing with pre-and post-conditions© 2003 David Holmes and Doug Lea79Interfaces and Policiespublic interface Buffer{int capacity();// Inv: capacity() > 0int size();// Inv: 0 size() capacity()// Init: size() == 0void put(Object x);// Pre: size() < capacity()Object take();// Pre: size() > 0}Interfaces alone cannot convey policyBut can suggest policyFor example, should take()throw exception? What kind?Different methods can support different policies for same base actionsBut can use manual annotationsDeclarative constraints form basis for implementationFor examples we throw Failure:class Failure extends Exception {...}© 2003 David Holmes and Doug Lea80BalkingCheck state upon method entry Must not change state in course of checking itRelevant state must beexplicitly represented, so can be checked upon entryExit immediately if not in right stateThrow exception or return special error valueClient is responsible for handling failureThe simplest policy for fully synchronized objectsUseable in both sequential and concurrent contextsOften used in Collection classes (Vector, etc)In concurrent contexts, the host must always take responsibility for entire check-act/check-fail sequenceClients cannot preclude state changes between check and act, so host must control© 2003 David Holmes and Doug Lea81Example: Balking Bounded Bufferpublic class BalkingBoundedBufferimplements Buffer {private List data;private final intcapacity;public BalkingBoundedBuffer(intcapacity) {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 intsize() { return data.size();}public intcapacity() {return capacity;}}USENIX COOTS '98April 27, 1998Designing Concurrent Object-Oriented Programs in Java3© 2003 David Holmes and Doug Lea82GuardingCheck state upon entry If 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


View Full Document

UMD CMSC 433 - Designing Objects for Concurrency

Documents in this Course
Trace 1

Trace 1

62 pages

Reflection

Reflection

137 pages

Testing

Testing

25 pages

Paradigms

Paradigms

10 pages

Testing

Testing

17 pages

Java RMI

Java RMI

17 pages

Java RMI

Java RMI

17 pages

Java RMI

Java RMI

17 pages

Trace 1

Trace 1

46 pages

Jini

Jini

4 pages

Final

Final

15 pages

Java RMI

Java RMI

13 pages

Testing

Testing

16 pages

Load more
Download Designing Objects for Concurrency
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Designing Objects for Concurrency and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Designing Objects for Concurrency 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?