CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects

Similar documents
Sharing Objects Ch. 3

Lecture 17: Sharing Objects in Java

Sharing Objects. Java and Android Concurrency.

Advanced concurrent programming in Java Shared objects

Get out, you will, of this bind If, your objects, you have confined

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

The Java Memory Model

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

Concurrency WS 2010/2011 The Java Memory Model

Question Points Score Total 100

Threads and Parallelism in Java

Introduction to Locks. Intrinsic Locks

System Programming. Practical Session 4: Threads and Concurrency / Safety

Question Points Score Total 100

Java Platform Concurrency Gotchas

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

CMSC 433 Programming Language Technologies and Paradigms. Synchronization

CMSC 132: Object-Oriented Programming II

Multiple Inheritance. Computer object can be viewed as

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Threads Questions Important Questions

Safety SPL/2010 SPL/20 1

The New Java Technology Memory Model

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

CMSC 433 Spring 2013 Exam 1

Modeling Process. Rich Hickey

Principles of Software Construction: Objects, Design and Concurrency. Mutability and Java Potpourri. toad Fall 2013

Modular Reasoning about Aliasing using Permissions

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, Instructions

Design of Thread-Safe Classes

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Michele Van Dyne MUS 204B Concurrency Issues

Advanced MEIC. (Lesson #18)

CS 159: Parallel Processing

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

What is a thread anyway?

CMSC 330: Organization of Programming Languages

Synchronization SPL/2010 SPL/20 1

1.00 Lecture 29. Sensors and Threads. Reading for next time: Numerical Recipes (online)

Concurrency. Fundamentals of Computer Science

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

CMSC 330: Organization of Programming Languages

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Notes on Chapter Three

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

CSE331 Winter 2014, Midterm Examination February 12, 2014

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Principles of Software Construction: Concurrency, Part 2

User Space Multithreading. Computer Science, University of Warwick

CSE 374 Programming Concepts & Tools

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

Using Java 8 Lambdas And Stampedlock To Manage Thread Safety

The Singleton Pattern. Design Patterns In Java Bob Tarr

7. MULTITHREDED PROGRAMMING

Favoring Isolated Mutability The Actor Model of Concurrency. CSCI 5828: Foundations of Software Engineering Lecture 24 04/11/2012

Josh Bloch Charlie Garrod Darya Melicher

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Persistent Data Structures and Managed References

Java Threads. 02/05/2007 CSCI 315 Operating Systems Design 1

Programmazione di sistemi multicore

CMSC 132: Object-Oriented Programming II. Threads in Java

Classes Classes 2 / 36

Concurrency CSCI 201 Principles of Software Development

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections

t=t + "g"; On the other hand, arrays are mutable. The assignment a[i]=e/// where e element is equal 6

Finding Concurrency Bugs in Java

Identity, State and Values

Lecture 10 State dependency

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Configuration Provider: A Pattern for Configuring Threaded Applications

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Grafting Functional Support on Top of an Imperative Language

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Exercise Session Week 8

CST242 Concurrency Page 1

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Reintroduction to Concurrency

Synchronization

Applied Unified Ownership. Capabilities for Sharing Across Threads

Problems with Concurrency. February 19, 2014

Consistency. CS 475, Spring 2018 Concurrent & Distributed Systems

Transcription:

CMSC 433 Programming Language Technologies and Paradigms Sharing Objects

Administrivia Are you getting your money s worth? Are you reviewing the slides? Are you experimenting with concurrency? Have you downloaded the source code examples from class repo and from JCIP? Have you run some concurrent programs? Have you written some concurrent programs?

Volatile Fields Use volatile variables only when: Writes don t depend on current value, or you can ensure that only a single thread ever updates the value The variable does not participate in invariants with other state variables Locking is not needed while the variable is being accessed

Publication & Escape Publishing an object means making it available outside its current context e.g., storing it externally, returning, passing it as a parameter If you publish an object when you shouldn t that the object has escaped If Object obj escapes, everything reachable from obj has escaped too

Example class Secrets { public static Set<Secret> knownsecrets; public void initialize() { knownsecrets = new HashSet<Secret>(); knownsecrets is public, so all entries have escaped

ListenerClass public class ListenerClass { public ListenerClass(EventSource source) { source.registerlistener(new EventListener() { public void onevent(event e) { dosomething(e); ); interface EventListener { void onevent(event e); this reference escapes with inner class EventListener

Safe Construction Practices Don t let the this reference escape during object construction Avoid creating and then starting a thread in a constructor

this Reference Escapes public class RunnableExample { class RunnableThread implements Runnable { Thread runner; public RunnableThread() { runner = new Thread(this); runner.start(); public static void main(string[] args) { RunnableThread thread3 = new RunnableThread();

Better Listener public class SafeListener { private final EventListener listener; private SafeListener() { listener = new EventListener() { public void onevent(event e) { dosomething(e); ; public static SafeListener newinstance(eventsource source) { SafeListener safe = new SafeListener(); source.registerlistener(safe.listener); return safe;

Thread Confinement If an object is only accessed in a single thread, you don t have to synchronize access to it Some designs partition activities or tasks into individual threads Ad-hoc Confinement Stack Confinement ThreadLocal

Ad-hoc Thread Confinement public class ThreadPerConnectionServer extends LoggingServerCore { public void process(datarecord record) { (new Thread(new StdOutMsgHandler(record))).start();

Ad-hoc Thread Confinement public class StdOutMsgHandler extends MsgHandler { public StdOutMsgHandler(DataRecord record) { super(record); public void run() { System.out.println("Server Side: writing record:" + record);

Stack Confinement Ad-hoc confinement can t be enforced Stack confinement Make objects accessible only through local variables

Stack Confinement public class Matches { // assumes entries is not modified during operation public List<Integer> matches (List<Integer> entries, Integer val) { ArrayList<Integer> matchlist = new ArrayList<Integer>(); for (Integer entry : entries) { if (entry == val) { matchlist.add(entry); return matchlist;

ThreadLocal Suppose you have multiple web server objects, where each runs in its own thread, and each can serve pages from different document directories Could define a docroot field in WebServer class Or, define the docroot 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 All methods running in the thread access docroot No interference because ALL accesses to a given docroot are within same thread

ThreadLocal public class WebServerThread { static final ThreadLocal docroot = new ThreadLocal();... public WebServerThread(int port, File root) {... docroot.set(root); processrequestwithwebserver(webserver,request) public class WebServer { public void proces(request) File root = (File) WebServerThread.docRoot.get(); // service request

ThreadLocal Use for variables that apply per-activity, not per-object e.g., Timeout values, transaction IDs, current directories, default parameters Use as replacements for static variables When different threads should use different values

Immutability Immutable objects are always thread safe An object is immutable if: Its state can t be modified after construction Its fields are all final It is properly constructed

Final Fields Are initialized once, but never changed Allow programmers to implement thread-safe immutable objects without synchronization An object is considered to be completely initialized when its constructor finishes A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see correctly initialized values for that object's final fields

Unsafe Publication public class Holder { private int n; public Holder(int n) { this.n = n; public void assertsanity() { assert (n == n); public class User{ public Holder holder; public void initialize() { holder = new Holder(42);

Unsafe Publication To another thread, the holder object could appear to be incompletely constructed The reference could be stale (null) The fields in the Holder object could be stale

Safe Publication Idioms Mutable objects must be safely published Requires synchronization by both publishing and using threads To publish safely both an object s reference and its state must be made visible to other threads at the same time

Safe Publication Idioms A properly constructed object can be safely published by: Initializing an object reference from a static initializer Storing a reference to it into a volatile field or AtomicReference Storing a reference to it into a final field of a properly constructed object Storing a reference to it into a field that is properly guarded by a lock

Effectively Immutable Objects Objects that are not immutable, but are not modified after publication can be thought of as effectively immutable Safely published effectively immutable objects can be used safely by any thread without additional synchronization

Mutable Objects Safe publication ensures visibility of an object at the time it s published All subsequent accesses must be synchronized

Safe Publishing Publication requirements depend on mutability status Immutable any mechanism Effectively Immutable must be safely published Mutable safely published and thread safe or all accesses guarded by a lock

Sharing Objects Safely Some Policies for using and sharing objects in a concurrent program Thread-confined Object owned and used exclusively in 1 thread Shared read-only Object can be freely shared, but can t be modified Shared thread safe Object performs its own synchronization, so can be freely shared Guarded Object can accessed only if a specific lock is held