a980b2efdc693e323fc0958b1243d1b7.ppt
- Количество слайдов: 24
System Programming Practical Session 4: Concurrency / Safety
Threads Till now, no multithreading class Prog{ public static void main(String args []){ ……. func 1(); func 2(); }
Threads Step 1. Implement the interface Runnable: interface Runnabe{ public void run(); } Step 2. option 1: Create Threads option 2: Use Executor
Step 1 Example class Simple. Runnable implements Runnable { private int m_number; public Simple. Runnable(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 Threads 01 { public static void main(String[] a) { Simple. Runnable r 1 = new Simple. Runnable(1); Thread t 1 = new Thread(r 1); Simple. Runnable r 2 = new Simple. Runnable(2); Thread t 2 = new Thread(r 2); t 1. start(); t 2. start(); } } Output: 1 1 2 2 2 1 1 2 2 1 1
Step 2. Option 2 - Executor. Service. example public class Threads 01 e { public static void main(String[] a) { // Create an executor: Executor. Service e = Executors. new. Fixed. Thread. Pool(3); // create several runnables, and execute them. for(int i=0; i<10; i++) { Simple. Runnable r = new Simple. Runnable(i); e. execute(r); } e. shutdown(); } }
Threads can be Dangerous Example: Two teaching assistants and one electronic Announcements page. Announcments A A B B C C Y TA 1 downloads page Time TA 2 downloads page Adds msg X Adds msg Y upload
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. * @param i line number * @param s the string to concatenate */ public void print. ALine(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 Simple. Asynchronous. Task implements Runnable { Printer m_p; String m_name; Simple. Asynchronous. Task(String name, Printer p) { m_p = p; m_name = name; } public void run() { for (int i = 0; i<50; i++) { m_p. print. ALine(i, m_name); } }
Example 1 continued public class Threads 02 { static void main(String[] a) { Printer p = new Printer(); Thread t 1 = new Thread(new Simple. Asynchronous. Task("a", p) ); Thread t 2 = new Thread(new Simple. Asynchronous. Task("b", p) ); t 1. start(); // prints some lines of aaaa t 2. start(); // prints some lines of bbbb } }
Example 2: Even counter import java. util. concurrent. *; class Even. Task implements Runnable { Even m_even; Even. Task(Even even) { m_even = even; } public void run() { for (int i = 0; i < 50; i++) { System. out. println(m_even. next()); } } } public class Threads 03 { public static void main(String[] args) { Executor. Service e = Executors. new. Fixed. Thread. Pool(10); Even ev = new Even(); for (int i=0; i<10; i++) { e. execute(new Even. Task(ev)); } e. shutdown(); } } class Even { private long n = 0; //@ pre-condition: n is even public long next() { n++; try {Thread. sleep(30); } catch (Interrupted. Exception e) { } n++; return n; //@ post-condition : n is greater by two }
Solution (Trial) class Even. Task implements Runnable { Even m_even; Even. Task(Even even) { m_even = even; } public void run() { try { for (int i = 0; i < 50; i++) { System. out. println( m_even. next()); } } catch (Not. Even. Exception e) { System. out. println("Exception in “ + Thread. current. Thread(). get. Name()); e. print. Stack. Trace(System. out); } } } class Not. Even. Exception extends Exception { public Not. Even. Exception (String message){ super(message); } } class Even { private long n = 0; //@ pre-condition: n is even public long next() throws Not. Even. Exception { if (n%2 != 0) { throw new Not. Even. Exception( "PRE: n is not even!"); } n++; try {Thread. sleep(30); } catch (Interrupted. Exception e) {} n++; if (n%2 != 0) { throw new Not. Even. Exception( "POST: n is not even!"); } return n; } //@ post-condition : n is greater in two }
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 Class. A { 4. public long i; 5. public Vector v; 6. public Class. A (){/*…*/} 7. public void do. Something( 8. 1. 2. 3. 4. 5. 1. 2. 3. long x, List lst){ long local. Var = 0; Object o ; o = this. v. element. At(2); // 1 local. Var += 2; // 2 this. i += 2; // 3 x += 2; // 4 lst. element. At(2); // 5 Foo. NUMBER = 4; // 6 local. Var = Foo. NUMBER; // 7 1. class Task. A implements Runnable { 2. private Class. A a; 3. private List lst; 4. public long r; 5. //… some code …. 6. public void run(){ 7. this. r = 2; // 8 8. this. a. do. Something( 9. 9, lst); // 9 10. 8. } 11. 9. } 12. 10. class Main { 13. 11. public static void main( String[] args){ 14. 13. Class. A o 1 = new Class. A(); 15. Thread t 1 = 16. new Thread(new Task. A(o 1)); 17. 15. t 1. start(); 18. //…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 Thread. Confined. Example 2. { 3. //Thread. Confined 4. public Car create. Car() { 5. Engine e = new Fuel. Engine(); 6. List
1. public class Thread. Not. Confined. Example 2. { 3. //Not. Thread. Confined 4. public Car create. Car(Engine e){ 5. List
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 Class. A{ …………. . public void set. B(Class. B obj. B) { … } ……… } Public class Class. B{ …………… public Class. B(Class. A obj. A){ //constructor …………… obj. A. set. B(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 Three. Stooges { private final Set
Summary The most useful policies for using and sharing objects in a concurrent program are: • Thread-confined • Shared read-only • Shared thread-safe


