System Programming Practical Session 4: Concurrency / Safety.

Slides:



Advertisements
Similar presentations
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Advertisements

1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Effective Java: Concurrency Last Updated: Fall 2011.
System Programming Practical Session 5 Liveness, Guarded Methods, and Thread Timing.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Assignment – no class Wednesday All: watch the Google Techtalk “Getting C++ Threads Right” by Hans Boehm at the following link in place of Wednesday’s.
Access to Names Namespaces, Scopes, Access privileges.
1 Where did the synchronized methods go? Yes, there still exists the synchronized keyword. public synchronized void foo() {} public void foo(){ aLock.lock();
16-Jun-15 Java Threads Fine grained, shared state.
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
Week 9 Building blocks.
System Programming Web site: Things to know Weekly Homework Each practical session.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
Session 7 Methods Strings Constructors this Inheritance.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
SPL/2010 Synchronization 1. SPL/2010 Overview ● synchronization mechanisms in modern RTEs ● concurrency issues ● places where synchronization is needed.
COMPSCI 230 S2C 2015 Software Design and Construction Synchronization (cont.) Lecture 4 of Theme C.
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Software and Threading Geza Kovacs Maslab Abstract Design: State Machines By using state machine diagrams, you can find flaws in your behavior without.
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
System Programming Practical Session 4: Concurrency / Safety.
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
More on Thread Safety CSE451 Andrew Whitaker. Review: Thread Hazards Safety hazards  “Program does the wrong thing” Liveness hazards  “Program never.
תכנות מערכות תרגול 1 נושאי התרגול: - חשבון משתמש Linux - Threads.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Concurrent Programming Acknowledgements: Some slides adapted from David Evans, U. Virginia.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Staples are our staple Building upon our solution.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Monitor Pattern Read only Collection views Synchronized Collections views Concurrent HashMap The Vehicle Tracker Example.
Sun Proprietary/Confidential: Internal Use Only 1 Multi-Threading Primer Byron Nevins December 10, 2007.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 2: Data Types, Variables, Operators, and Expressions
System Programming Practical Session 7
Lecture 8 Thread Safety.
March 29th Odds & Ends CS 239.
Condition Variables and Producer/Consumer
CNT 4007C Project 2 Good morning, everyone. In this class, we will have a brief look at the project 2. Project 2 is basically the same with project 1.
Condition Variables and Producer/Consumer
More on Thread Safety CSE451 Andrew Whitaker.
Java Concurrency 17-Jan-19.
Recap Week 2 and 3.
Final Jim Brucker.
Java Concurrency.
Java Concurrency.
Lecture 8 Thread Safety.
Java Concurrency 29-May-19.
Problems with Locks Andrew Whitaker CSE451.
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
Threads and concurrency / Safety
Presentation transcript:

System Programming Practical Session 4: Concurrency / Safety

Safety Running several threads in parallel is not safe. Unpredictable results on shared resources. Design aproaches towards avoiding safety problems Thread confinement Immutability Locking / Synchronization

Shared Resources Shared resource - A resource that is visible to several threads. Objects that may be visisble to several threads - Are not safe. Objectst that cannot be shared (local function variables) - Are safe.

1.class Foo{ 2. public static double NUMBER = 33.3; } 3.class ClassA { 4.public long i; 5.public Vector v; 6.public ClassA (){/* … */} 7.public void doSomething( long x, List lst){ 8. long localVar = 0; 9. Object o; 10. o = this.v.elementAt(2); // localVar += 2; // this.i += 2; // x += 2; // lst.elementAt(2); // Foo.NUMBER = 4; // localVar = Foo.NUMBER; // } } 1.class TaskA implements Runnable { 2. private ClassA a; 3. private List lst; 4. public long r; 5.// … some code …. 6. public void run(){ 7. this.r = 2; // 8 8. this.a.doSomething( 9, lst); // 9 8. } 9. } 10. class Main { 11. public static void main( String[] args){ 13. ClassA o1 = new ClassA(); 14. Thread t1 = new Thread(new TaskA(o1)); 15. t1.start(); 16. // … some code …. } }

Thread Confinement A resource that is used exclusively by a one single thread is confined to the thread. If all the resources of a method are confined, then it is safe.

1.public class ThreadConfinedExample 2. { 3. //ThreadConfined 4. public Car createCar() { 5. Engine e = new FuelEngine(); 6. List doors = new LinkedList (); 7. doors.add(new FrontDoor()); 8. doors.add(new FrontDoor()); 9. doors.add(new BackDoor()); 10. doors.add(new BackDoor()); 11. Radio r = new AMFMRadio(); Car c = new Car(e, doors, r); return c; 16. } 17.}

1.public class ThreadNotConfinedExample 2. { 3. // NotThreadConfined 4. public Car createCar(Engine e){ 5. List doors = new LinkedList ; 6. doors.add(new FrontDoor()); 7 doors.add(new FrontDoor()); 8. doors.add(new BackDoor()); 9. doors.add(new BackDoor()); 10. Radio r = new AMFMRadio()); Car c = new Car(e, doors, r); return c; 15. } 16.}

Immutability An immutable object’s state cannot be changed after construction. Examples: String Integer

Immutability An object is immutable if All primitive fields are final. All other fields are references to immutable objects. The object has been safely published: Reference to this hasn't escaped during construction. No thread has accessed the object before the construction completed.

‘this’ escape example Public class ClassA{ ………….. public void setB(ClassB objB) { … } ……… } Public class ClassB{ …………… public ClassB(ClassA objA){ //constructor …………… objA.setB(this); } …………… }

Immutability An object with references to mutable objects can still be immutable! A class will be immutable if all of the following are true: 1.All of its fields are final 2.The class is declared final 3.The this reference is not allowed to escape during construction 4.Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes: Are private Are never returned or otherwise exposed to callers Are the only reference to the objects that they reference Do not change the state of the referenced objects after construction

public final class ThreeStooges { private final Set stooges = new HashSet (); public ThreeStooges() { stooges.add("Moe"); stooges.add("Larry"); stooges.add("Curly"); } public boolean isStooge(String name) { return stooges.contains(name); }

Synchronization A mechanism allowing safely accessing shared resources. A thread accessing a synchronized method locks the object. The object cannot be accessed by other threads while it is locked.

Synchronization 1. Class Even{ 2. private long n = 0; 3. public long next(){ 4. n++; 5. n++; 6. return n; 7. } 8. }

Synchronization 1. Class Even{ 2. private long n = 0; 3. public synchronized long next(){ 4. n++; 5. n++; 6. return n; 7. } 8. }

Synchronizing a block 1.public int foo() { 2. // do something safe 3. synchronized(this) { 4. // do something 5. return 9; 6. } 7. }

Solution to safety problem Printer Example (from practical session 1) 1.class Printer { 2. Printer() {} 3. /** 4. i line number 5. s the string to concatenate 40 times 6. */ 7. public synchronized void printALine(int i, String s) { 8. System.out.print(i + ") "); 9. for (int j = 0; j < 40; j++) { 10. System.out.print(s); 11. } 12. System.out.println(); 13. } 14.}

1.public class GoodSynchronization{ 2. public static void main(String[] a) { 3. Printer p = new Printer(); 4. Thread t1 = new Thread( new SimpleAsynchronousTask("a", p) ); 5. Thread t2 = new Thread( new SimpleAsynchronousTask("b", p) ); 6. t1.start(); // prints some lines of aaaa 7. t2.start(); // prints some lines of bbbb 8. } } 9.class SimpleAsynchronousTask implements Runnable { 10. Printer m_p; 11. String m_name; 12. public SimpleAsynchronousTask(String name, Printer p) { 13. m_p = p; 14. m_name = name; 15. } 16. public void run() { 17. for (int i = 0; i<50; i++) { 18. m_p.printALine(i, m_name); 19. } 20. } }

Wrong solution #1 1.public class BadSynchronization2 2. public static void main(String[] a) { 3. Printer p1 = new Printer(); 4. Printer p2 = new Printer(); 5. Thread t1 = new Thread( new SimpleAsynchronousTask("a", p1) ); 6. Thread t2 = new Thread( new SimpleAsynchronousTask("b", p2) ); t1.start(); // prints some lines of aaaa 9. t2.start(); // prints some lines of bbbb 10. } 11.} class SimpleAsynchronousTask implements Runnable { the same like GoodSynchronization.java 15.class Printer { the same like GoodSynchronization.java 17.}

Wrong solution #2 (no printer object) 1.class BadSynchronization { 2. public static void main(String[] a) { 3. Thread t1 = new Thread( new SimpleAsynchronousTask("a") ); 4. Thread t2 = new Thread( new SimpleAsynchronousTask("b") ); 5. t1.start(); // prints some lines of aaaa 6. t2.start(); // prints some lines of bbbb 7. } 8.} class SimpleAsynchronousTask implements Runnable { the same like GoodSynchronization.java 12. public synchronized void printALine(int i, String s) { 13. System.out.print(i + ") "); 14. for (int j = 0; j < 40; j++) System.out.print(s); 15. System.out.println(); 16. } 17.}

Summary The most useful policies for using and sharing objects in a concurrent program are: Thread-confined Shared read-only Shared thread-safe