System Programming Practical Session 4: Concurrency / Safety.

Slides:



Advertisements
Similar presentations
Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
Advertisements

Concurrency 101 Shared state. Part 1: General Concepts 2.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
©SoftMoore ConsultingSlide 1 Appendix D: Java Threads "The real payoff of concurrent execution arises not from the fact that applications can be speeded.
System Programming Practical Session 5 Liveness, Guarded Methods, and Thread Timing.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
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.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
System Programming Web site: Things to know Weekly Homework Each practical session.
Lecture 4 : JAVA Thread Programming
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Addendum to Lab 10 What was all that about?. Consider… A static queue class – It has one copy of the queue in the class’s memory : public class StaticQClass.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Multiprocessor Cache Consistency (or, what does volatile mean?) Andrew Whitaker CSE451.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
תכנות מערכות תרגול 1 נושאי התרגול: - חשבון משתמש Linux - Threads.
System Programming Practical Session 4: Concurrency / Safety.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
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.
Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Multithreading.
Practice Session 8 Lockfree LinkedList Blocking queues
Section 5.7 Concurrency, Interference, and Synchronization.
System Programming Practical Session 7
Lecture 8 Thread Safety.
Threads Chate Patanothai.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
More on Thread Safety CSE451 Andrew Whitaker.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Java Concurrency 17-Jan-19.
Threads in Java James 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

Threads Till now, no multithreading class Prog{ public static void main(String args []){ ……. func1(); func2(); }

Threads Step1. Implement the interface Runnable: interface Runnabe{ public void run(); } Step 2. option 1: Create Threads option 2: Use Executor

Step 1 Example class SimpleRunnable implements Runnable { private int m_number; public SimpleRunnable(int i) { this.m_number = i; } public void run() { for (int i = 0; i < 10; i++) { System.out.print(" " + m_number); }

Step 2. Option 1. example public class Threads01 { public static void main(String[] a) { SimpleRunnable r1 = new SimpleRunnable(1); Thread t1 = new Thread(r1); SimpleRunnable r2 = new SimpleRunnable(2); Thread t2 = new Thread(r2); t1.start(); t2.start(); } Output:

Step 2. Option 2 - ExecutorService. example public class Threads01e { public static void main(String[] a) { // Create an executor: ExecutorService e = Executors.newFixedThreadPool(3); // create several runnables, and execute them. for(int i=0;i<10;i++) { SimpleRunnable r = new SimpleRunnable(i); e.execute(r); } e.shutdown(); }

Threads can be Dangerous Example: Two teaching assistants and one electronic Announcements page. Time Announcments A B C TA1 downloads page TA2 downloads pageAdds msg Y Adds msg Xupload Announcments A B C Y

Threads can be Dangerous Code Example 1: One printer and two threads class Printer { Printer() { } /** * Print a numbered line of the string 's' 40 times. i line number s the string to concatenate */ public void printALine(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) { System.out.print(s); } System.out.println(); }

Example 1 continued class SimpleAsynchronousTask implements Runnable { Printer m_p; String m_name; SimpleAsynchronousTask(String name, Printer p) { m_p = p; m_name = name; } public void run() { for (int i = 0; i<50; i++) { m_p.printALine(i, m_name); }

Example 1 continued public class Threads02 { static void main(String[] a) { Printer p = new Printer(); Thread t1 = new Thread(new SimpleAsynchronousTask("a", p) ); Thread t2 = new Thread(new SimpleAsynchronousTask("b", p) ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb }

Example 2: Even counter import java.util.concurrent.*; class EvenTask implements Runnable { Even m_even; EvenTask(Even even) { m_even = even; } public void run() { for (int i = 0; i < 50; i++) { System.out.println(m_even.next()); } } } public class Threads03 { public static void main(String[] args) { ExecutorService e = Executors.newFixedThreadPool(10); Even ev = new Even(); for (int i=0; i<10; i++) { e.execute(new EvenTask(ev)); } e.shutdown(); } } class Even { private long n = 0; pre-condition: n is even public long next() { n++; try {Thread.sleep(30);} catch (InterruptedException e) { } n++; return n; post-condition : n is greater by two }

Solution (Trial) class EvenTask implements Runnable { Even m_even; EvenTask(Even even) { m_even = even; } public void run() { try { for (int i = 0; i < 50; i++) { System.out.println( m_even.next()); } } catch (NotEvenException e) { System.out.println("Exception in “ + Thread.currentThread().getName()); e.printStackTrace(System.out); } } } class Even { private long n = 0; pre-condition: n is even public long next() throws NotEvenException { if (n%2 != 0) { throw new NotEvenException( "PRE: n is not even!"); } n++; try {Thread.sleep(30);} catch (InterruptedException e) {} n++; if (n%2 != 0) { throw new NotEvenException( "POST: n is not even!"); } return n; } post-condition : n is greater in two } class NotEvenException extends Exception { public NotEvenException (String message){ super(message); } }

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 visible 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 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); }

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