Die Präsentation wird geladen. Bitte warten

Die Präsentation wird geladen. Bitte warten

Prof. Dr. Alois Schütte Advanced System Programming 1 Das concurrent Paket 1 Überblick 2 Lock 3 Condition 4 Queue 5 Executors.

Ähnliche Präsentationen


Präsentation zum Thema: "Prof. Dr. Alois Schütte Advanced System Programming 1 Das concurrent Paket 1 Überblick 2 Lock 3 Condition 4 Queue 5 Executors."—  Präsentation transkript:

1 Prof. Dr. Alois Schütte Advanced System Programming 1 Das concurrent Paket 1 Überblick 2 Lock 3 Condition 4 Queue 5 Executors

2 Prof. Dr. Alois Schütte Advanced System Programming 2 Concurrrent Paket: 1 Überblick  Standard-Mittel von Java bezogen auf Nebenläufigkeit sind:  Threads mit dem Interface Runnable  Synchronisations-Mechanismen synchronized, wait, notify und notifyAll.  Ab Java 5 sind im Paket java.util.concurrent Klassen für Standard-Muster der parallelen Programmierung enthalten, z.B.:  Locks  Queues  Thread-Pooling  Scheduling  Semaphore  Exchanger  CountDownLatch  CyclicBarrier

3 Prof. Dr. Alois Schütte Advanced System Programming 3 Concurrrent Paket: 2 Locks  Lockkonzept  Ein Lock ist ein Mittel, um in multithreading Umgebungen den gemeinsamen Zugriff auf Ressourcen zu koordinieren.  Um eine Ressource nutzen zu können, muss ein Thread den zugehörigen Schlüssel anfordern.  Solange ein Thread den Schlüssel besitzt, kann kein anderer Thread die Ressource verwenden, er muss warten.  Der den Schlüssel besitzende Thread gibt ihn frei, daraufhin kann ein wartender Thread den Schlüssel bekommen und die Ressource verwenden.  Dieses Lockkonzept könnte mit synchronized umgesetzt werden. Dabei hat man aber immer die Blockstruktur als Einschränkung.  java.util.concurrent.locks beinhaltet Interfaces und Klassen für Locks.

4 Prof. Dr. Alois Schütte Advanced System Programming 4 Concurrrent Paket: 2 Locks  Die Klasse TimeUnit wird im Zusammenhang mit Locks verwendet, um eine Zeitdauer in SECONDS, MICROSECONDS, MILLISECONDS oder NANOSECONDS angeben zu können.  Class TimeUnit Class TimeUnit  Beispiel:TimeUnit/MainClass.javaTimeUnit/MainClass.java 1. import static java.util.concurrent.TimeUnit.*; 2. public class MainClass extends Thread { 3. // This field is volatile because two different threads may access it 4. volatile boolean keepRunning = true; 5. public void run() { 6. while (keepRunning) { 7. long now = System.currentTimeMillis(); 8. System.out.printf("%tr%n", now); 9. try { Thread.sleep(1000); // millisecs 10. } catch (InterruptedException e) { 11. return; 12. } 13. } 14. } // run

5 Prof. Dr. Alois Schütte Advanced System Programming 5 Concurrrent Paket: 2 Locks 15. public void pleaseStop() { 16. keepRunning = false; 17. } 18. public static void main(String[] args) { 19. MainClass thread = new MainClass(); 20. thread.start(); 21. try { SECONDS.sleep(10); // = MILLISECONDS.sleep(10000) 22. } catch (InterruptedException ignore) { 23. } 24. thread.pleaseStop(); 25. } // main 26. } as@hal:TimeUnit> java MainClass 10:19:51 AM 10:19:52 AM 10:19:53 AM 10:19:54 AM 10:19:55 AM 10:19:56 AM 10:19:57 AM 10:19:58 AM 10:19:59 AM 10:20:00 AM as@hal:TimeUnit>

6 Prof. Dr. Alois Schütte Advanced System Programming 6 Concurrrent Paket: 2 Locks  Das Interface Lock spezifiziert das Verhalten von Lock-Objekten. public interface Lock { void lock(); void lockInterruptible() throws InterruptedException; boolean tryLock(); boolean tryLock(long time, TimeUnit unit) throws InterruptedException void unlock(); Condition newCondition(); // Erklärung später }  lock wartet, bis der Objektschlüssel verfügbar ist und belegt ihn dann.  unlock gibt das Objekt frei.  lockInterruptible funktioniert wie lock, aber es wird eine Ausnahme geworfen, wenn ein anderer Thread den Thread durch interrupt unterbricht.  tryLock liefert false, wenn das Objekt nicht verfügbar ist; ansonsten wird das Objekt in Besitz genommen und true returniert.  tryLock(long, TimeUnit) funktioniert wie tryLock, aber es wird eine maximale Zeitspanne gewartet, wenn das Objekt nicht verfügbar ist.

7 Prof. Dr. Alois Schütte Advanced System Programming 7 Concurrrent Paket: 2.1 ReentrantLock  Die Klasse ReentrantLock implementiert die Schnittstelle Lock. public class ReentrantLock implements Lock, Serializable { public ReentrantLock(boolean fair); public ReentrantLock; // Methods of Lock void lock(); void lockInterruptible() throws InterruptedException; boolean tryLock(); boolean tryLock(long time, TimeUnit unit) throws InterruptedException void unlock(); Condition newCondition(); // additional Methods public boolean isFair(); public int getHoldCount(); public int getQueueLength(); public boolean isHeldByCurrentThread(); public boolean isLocked(); protected Thread getOwner(); protected Collection getQueuedThreda(); }

8 Prof. Dr. Alois Schütte Advanced System Programming 8 Concurrrent Paket: 2.1 ReentrantLock  Der Konstruktor kann die Angabe eine fair-Paramerters haben. Wenn mehere Threads auf den Lock warten, garantiert fair==true, dass der am längsten wartende Thread das Lock-Objekt erhält.  isFair liefert den fair-Parameter des Konstruktors zurück.  Ein Lock enthält eine Zähler, der bei jedem lock inkrementiert, bei unlock dekrementiert wird. Ein Thread kann also öfter lock aufrufen. getHoldCount liefert den Wert des Zählers.  getQueueLength returniert die Anzahl der auf einen Lock wartenden Threads.  isHeldByCurrentThread ist true, wenn der aufrufende Thread den Lock hält.  isLocked ist true, wenn irgendein Thread den Lock hält.  getOwner(), Collection getQueuedThreads liefern den Besitzer und die wartenden Threads.

9 Prof. Dr. Alois Schütte Advanced System Programming 9 Concurrrent Paket: 2.1 ReentrantLock  Beispiel: Klasse Konto (Account), Geldabholer (Withdrawer als Thread)Geldabholer  Zunächst die Realisierung der Klasse Account mit synchronized 1. class Account { 2. private float balance; 3. public Account (float initialBalance) { 4. balance = initialBalance; 5. } // Account 6. public synchronized float getBalance() { 7. return balance; 8. } // getBalance 9. public synchronized void withdraw( float amount) { 10. if (amount < 0 || balance < amount) 11. throw new IllegalArgumentException("withdraw: wrong amount " + amount); 12. try { Thread.sleep(1000); } catch (Exception e) {}; 13. balance -= amount; 14. } // withdraw 15. } // Account  synchronized ist erforderlich, da ein Konto von mehreren Threads verwendet werden kann und mindestens einer den Zustand per withdraw ändern kann.

10 Prof. Dr. Alois Schütte Advanced System Programming 10 Concurrrent Paket: 2.1 ReentrantLock  Geldabheber sind Threads, die vom Konto die withdraw-Methode verwenden. 1. class Withdrawer extends Thread { 2. private Account account; 3. private float amount; 4. Withdrawer (Account account, float amount) { 5. this.account = account; 6. this.amount = amount; 7. } 8. public void run () { 9. try { account.withdraw(amount); } 10. catch (Exception e) { System.out.println(e); } 11. } // run 12. } // Withdrawer

11 Prof. Dr. Alois Schütte Advanced System Programming 11 Concurrrent Paket: 2.1 ReentrantLock  Zwei Kontobevollmächtigte (Jenni und Hannah) wollen Geld vom gemeinsamen Konto abheben. 1. public class WithdrawApp { 2. public static void main(String[] args) throws InterruptedException { 3. Account account = new Account(1000); 4. Withdrawer hannah = new Withdrawer(account, 400); 5. Withdrawer jenni = new Withdrawer(account, 500); 6. hannah.start(); 7. jenni.start(); 8. hannah.join(); jenni.join(); 9. System.out.println("balance = " + account.getBalance()); 10. } 11. } as@hal:synchronized> java WithdrawApp balance = 100.0 as@hal:synchronized>

12 Prof. Dr. Alois Schütte Advanced System Programming 12 Concurrrent Paket: 2.1 ReentrantLock  Nun die Realisierung der Klasse Account mittels Locks.Realisierung  Die Blockstruktur von synchronized muss mittels lock und unlock nachgebildet werden: import java.util.concurrent.locks.*; private final ReentrantLock lock = new ReentrantLock(true); lock.lock(); try {... } finally { lock.unlock(); }  Wichtig:  Da im try-Block Ausnahmen auftreten können ist mittels finally sicherzustellen, dass stets unlock aufgerufen wird!  Nur so werden „gelockte“ Objekte immer freigegeben.  Die Verwendung von lock-unlock ist also aufwendiger, dafür aber universell: ein Thread kann lock aufrufen, ein andere unlock.  Soll anstelle einer Objektsperre eine Klassensperre deklariert werden, wird die Lock- Variable als static definiert.

13 Prof. Dr. Alois Schütte Advanced System Programming 13 Concurrrent Paket: 2.1 ReentrantLock 1. import java.util.concurrent.locks.*; 2. class Account { 3. private float balance; 4. private final ReentrantLock lock = new ReentrantLock(true); 5. public Account (float initialBalance) { 6. balance = initialBalance; 7. } // Account 8. public float getBalance() { 9. lock.lock(); 10. try { 11. return balance; 12. } 13. finally { 14. lock.unlock(); 15. } 16. } // getBalance 17. public void withdraw( float amount) { 18. lock.lock(); 19. try { 20. if (amount < 0 || balance < amount) 21. throw new IllegalArgumentException("withdraw:...); 22. try { Thread.sleep(1000); } catch (Exception e) {}; 23. balance -= amount; 24. } 25. finally { 26. lock.unlock(); 27. } 28. } // withdraw 29. } // Account

14 Prof. Dr. Alois Schütte Advanced System Programming 14 Concurrrent Paket: 2.1 ReentrantLock  Was muss geändert werden, wenn Jenni und Hannah nicht gleichzeitig Geld abholen dürfen?  Der erste Abholer hält den Lock, der zweite muss abgewiesen werden.  Lösung: Lösung  trylLock anstelle von lock 1. public void withdraw( float amount) { 2. if (lock.tryLock() == false) return; 3. try { 4. if (amount < 0 || balance < amount) 5. throw new IllegalArgumentException("withdraw:...); 6. try { Thread.sleep(1000); } catch (Exception e) {}; 7. balance -= amount; 8. } 9. finally { 10. lock.unlock(); 11. } 12. } // withdraw as@hal:synchronized> java WithdrawApp balance = 600.0 as@hal:synchronized>

15 Prof. Dr. Alois Schütte Advanced System Programming 15 Concurrrent Paket: 3 Condition  Die Methode newCondition des Interface Lock liefert ein Condition-Objekt zurück. Genauer, ein Objekt einer Klasse die die Schnittstelle Condition implementiert. 1. public interface Condition { 2. void await() throm InterruptedException; 3. void awaitUninterruptibly(); 4. boolean await(long time Timeunit unit) throm InterruptedException; 5. long awaitNanos(long time) throm InterruptedException; 6. boolean awaitUntil(Date deadline) throm InterruptedException; 7. void signal(); 8. void signalAll(); 9. }  Die Methoden haben Ähnlichkeit zu wait und notify.  Eine Condition ist signalisiert oder nicht signalisiert. Sofort nach ihrer Erzeugung ist sie signalisiert.  Ein await -Aufruf auf einer signalisierten Condition kehrt sofort zurück. Vor Rückkehr von await wird die Condition in den nicht signalisierten Zustand versetzt.  signal versetzt eine Condition in den signalisierten Zustand, weckt also einen wartenden Thread  signalAll weckt alle auf die Condition wartenden Threads.

16 Prof. Dr. Alois Schütte Advanced System Programming 16 Concurrrent Paket: 3 Condition  Beispiel: BoundedBuffer, zunächst mit synchronizedBoundedBuffer 1. class BoundedBuffer { 2. private float[] buffer; 3. private int first, last; 4. private int numberInBuffer = 0, size; 5. 6. BoundedBuffer(int length) { 7. size = length; 8. buffer = new float[size]; 9. first = last = 0; 10. } 11. 12. public synchronized void dumpBuffer() { 13. System.err.print("Buffer: "); // use err channel to log 14. for (int i=(first+1)%size, j=0; j<numberInBuffer; j++, i=(i+1)%size) 15. System.err.print(buffer[i] + " "); 16. System.err.println(" "); 17. } 18.

17 Prof. Dr. Alois Schütte Advanced System Programming 17 Concurrrent Paket: 3 Condition 1. public synchronized void put(float item) throws InterruptedException { 2. while(numberInBuffer == size) wait(); 3. last = (last+1)%size; 4. numberInBuffer++; 5. buffer[last] = item; 6. dumpBuffer(); 7. notifyAll(); 8. } 9. 10. public synchronized float get() throws InterruptedException { 11. while(numberInBuffer == 0) wait(); 12. first = (first+1)%size; 13. numberInBuffer--; 14. dumpBuffer(); 15. notifyAll(); 16. return buffer[first]; 17. } 18. } // BoundedBuffer  Die Methoden put und get sind mittels synchronized synchronisiert.

18 Prof. Dr. Alois Schütte Advanced System Programming 18 Concurrrent Paket: 3 Condition 1. class Producer extends Thread { 2. private BoundedBuffer buffer; 3. public Producer(BoundedBuffer b) { 4. buffer = b; 5. } 6. public void run() { 7. for(int i = 0; i < 100; i++) { 8. try { buffer.put(i); 9. System.out.println("put " + i); 10. } catch (InterruptedException ingnored) {}; 11. } 12. } 13. } // Producer 14. class Consumer extends Thread { 15.... 16. public void run() { 17. for(int i = 0; i < 100; i++) { 18. try { float x = buffer.get(); 19. System.out.println("got " + x); 20. } catch (InterruptedException ingnored) {}; 21. } 22. } 23. } // Consumer  Ein Produzent ruft die put-Methode auf, ein Konsoment die get-Methode des gemeinsamen Buffers.

19 Prof. Dr. Alois Schütte Advanced System Programming 19 Concurrrent Paket: 3 Condition  Wie kann man dies nun mittels Condition realisieren und wo sind die Vorteile?Condition realisieren 1. class BoundedBuffer { 2. private float[] buffer; 3. private int first, last; 4. private int numberInBuffer = 0, size; 5. 6. private ReentrantLock lock = new ReentrantLock(); 7. private final Condition notFull = lock.newCondition(); 8. private final Condition notEmpty = lock.newCondition(); 9. 10. BoundedBuffer(int length) { 11.... 12. } 13. 14. public void dumpBuffer() { 15.... 16. }  Es gibt zwei Condition Attribute, notFull und notEmpty für das Objekt lock.

20 Prof. Dr. Alois Schütte Advanced System Programming 20 Concurrrent Paket: 3 Condition 1. public void put(float item) throws InterruptedException { 2. lock.lock(); 3. try { 4. while(numberInBuffer == size) notFull.await(); 5. last = (last+1)%size; 6. numberInBuffer++; 7. buffer[last] = item; 8. dumpBuffer(); 9. notEmpty.signal(); 10. } finally {lock.unlock();} 11. }  Wenn der Buffer voll ist, wird gewartet, bis eine Condition notFull signalisiert wird.  Nach dem Schreiben in den Buffer wird signaliert notEmpty.

21 Prof. Dr. Alois Schütte Advanced System Programming 21 Concurrrent Paket: 3 Condition 1. public float get() throws InterruptedException { 2. try { 3. lock.lock(); 4. while(numberInBuffer == 0) notEmpty.await(); 5. first = (first+1)%size; 6. numberInBuffer--; 7. dumpBuffer(); 8. notFull.signal(); 9. return buffer[first]; 10. } finally {lock.unlock();} 11. } 12. } // BoundedBuffer  Wenn der Buffer leer ist, wird gewartet, bis eine Condition notEmpty signalisiert wird.  Nach dem Lesen des Buffer wird signaliert notFull.  Insgesamt ist man also mit Locks und Conditions flexibler, man kann unterschiedliche Bedingungen signalisieren und so gezielt nur bestimmte Threads wecken (eben die die auf die Condition warten).

22 Prof. Dr. Alois Schütte Advanced System Programming 22 Concurrrent Paket: 4 Executors  Bisher gab es stets eine enge Verbindung, zwischen dem was ein Thread macht (definiert im Runnable Objekt) und dem Thread selbst.  Beispiel HelloWorldHelloWorld 1. public class HelloWorld { 2. public static void main (String args [ ]) { 3. HelloWorldThread t = new HelloWorldThread ("Hello, World!"); 4. new Thread(t).start(); // creation and starting a thread 5. } 6. } 7. class HelloWorldThread implements Runnable { // task of a thread 8. private String str; 9. HelloWorldThread(String s) { 10. str = new String(s); 11. } 12. 13. public void run ( ) { 14. System.out.println(str); 15. } 16. }  In größeren Anwendungen macht es Sinn, strikt zwischen Thread- Management und Anwendungsfunktionalität des Thread zu unterscheiden.

23 Prof. Dr. Alois Schütte Advanced System Programming 23 Concurrrent Paket: 4 Executors  Objekte, die das Management von Threads übernehmen, werden Executors genannt.  Es existieren drei Schnittstellen für Executor:  Executor erlaubt das Erzeugen und Ausführen von Threads  ExecutorService ist ein Subinterface von Executor, das den Lebenszyklus von Thread beeinflussen kann  ScheduledExecutorService erlaubt das Definieren von zukünftigen oder periodischen Abläufen  Executor hat eine Methode execute, mit der ein Thread erzeugt und gestartet werden kann.  Wenn r ein Runnable Objekt ist und e ein Executor, dann gilt: (new Thread(r)).start(); == e.execute(r);  ExecutorService beinhaltet neben execute noch die Methode submit, die ebenfalls ein Runnable-Objekt aufnehmen kann. Zusätzlich ist die in der Lage, ein Callable- Objekt als Parameter zu erhalten. Ein Callable liefert einen Rückgabewert eines Thread. submit liefert ein Future -Objekt zurück, das verwendet wird um den Rückgabewert des Callable zu verarbeiten.  Die meisten der Executor-Schnittstellen-Implementieirungen benutzen Threadpools.

24 Prof. Dr. Alois Schütte Advanced System Programming 24 Concurrrent Paket: 4 Executors  Die Meisten Implementierungen der Executor-Schnittstellen benutzen Threadpools, die aus Workerthreads bestehen.  Die Idee ist es, eine Menge von Workerthreads zu haben, die einmal erzeugt werden und unterschiedliche Aufgaben im Verlauf der Zeit ausführen können.  Vorteil: die Threaderzeugung geschieht nur einmal  Alternativ müsste für jede Aufgabe immer ein Thread erzeugt werden, dann gelöscht werden, ein neuer Thread müsste erzeugt werden usw.  Es existieren unterschiedliche Arten von Threadpools. Hier sei eine stellvertretend behandelt.Threadpools  Bei einem fixed Threadpool gibt es eine feste Menge von Threads. Wenn mehrere Aufgabe zu bearbeiten sind, als Threads verfügbar sind, werden sie in eine Warteschlage eingereiht.  Beispiel 3 Aufgaben mit Pool von 2 Threads3 Aufgaben mit Pool von 2 Threads 1. import java.util.Random; 2. import java.util.concurrent.Executors; 3. import java.util.concurrent.ExecutorService;

25 Prof. Dr. Alois Schütte Advanced System Programming 25 Concurrrent Paket: 4 Executors 1. class PrintTask implements Runnable { 2. private int sleepTime; // random sleep time for thread 3. private String threadName; // name of thread 4. private static Random generator = new Random(); 5. // assign name to thread 6. public PrintTask(String name) { 7. threadName = name; // set name of thread 8. sleepTime = generator.nextInt(5000); // sleep time between 0 and 5 s 9. } // end PrintTask constructor 10. public void run() { 11. try { // put thread to sleep for sleepTime amount of time 12. System.out.printf("%s going to sleep for %d millisecs.\n", 13. threadName, sleepTime); 14. Thread.sleep(sleepTime); // put thread to sleep 15. } // end try 16. catch ( InterruptedException exception ) { 17. exception.printStackTrace(); 18. } // end catch 19. System.out.printf( "%s done sleeping\n", threadName ); 20. } // end method run 21. } // end class PrintTask

26 Prof. Dr. Alois Schütte Advanced System Programming 26 Concurrrent Paket: 4 Executors 1. public class Threadpool { 2. public static void main( String[] args ) { 3. // create and name each runnable 4. PrintTask task1 = new PrintTask( "thread 1" ); 5. PrintTask task2 = new PrintTask( "thread 2" ); 6. PrintTask task3 = new PrintTask( "thread 3" ); 7. System.out.println( "Starting threads" ); 8. // create ExecutorService to manage threads 9. ExecutorService threadExecutor = Executors.newFixedThreadPool( 2 ); 10. // start threads and place in runnable state 11. threadExecutor.execute( task1 ); // start task1 12. threadExecutor.execute( task2 ); // start task2 13. threadExecutor.execute( task3 ); // start task3 14. threadExecutor.shutdown(); // shutdown worker threads: no more worker 15. // allowed, but running worker run to complete 16. System.out.println( "Threads started, main ends\n" ); 17. } // end main 18. } // end class Threadpool as@hal:FixedThreadPool> java Threadpool Starting threads Threads started, main ends thread 1 going to sleep for 722 millisecs. thread 2 going to sleep for 4965 millisecs. thread 1 done sleeping thread 3 going to sleep for 3703 millisecs. thread 3 done sleeping thread 2 done sleeping as@hal:FixedThreadPool>


Herunterladen ppt "Prof. Dr. Alois Schütte Advanced System Programming 1 Das concurrent Paket 1 Überblick 2 Lock 3 Condition 4 Queue 5 Executors."

Ähnliche Präsentationen


Google-Anzeigen