JDK 1.5 全新的並行機制

56
JDK 1.5 JDK 1.5 全全全全全全全 全全全全全全全 全全全 / William Yeh [email protected] 2004.08.03. http://william.cswiz.org/present/20040803- javatwo

description

JDK 1.5 全新的並行機制

Transcript of JDK 1.5 全新的並行機制

  • JDK 1.5 / William [email protected]://william.cswiz.org/present/20040803-javatwo

    2004 Java2 *.

    Java Concurrency Facilitiesjava.langKeyword: synchronized

    2004 Java2 *.

    Concurrent Programming

    2004 Java2 *.

    Java Concurrent Programming 310 pagesScott Oaks, Henry Wong, Java Threads, 2nd edition, OReilly, 1999.344 pagesJeff Magee, Jeff Kramer, Concurrency: State Models & Java Programs, John Wiley & Sons, 1999.292 pagesAllen Holub, Taming Java Threads, Apress, 2000.376 pagesDoug Lea, Concurrent Programming in Java: Design Principles and Patterns, 2nd edition, Addison-Wesley, 1999.309 pagesVijay K. Garg, Concurrent and Distributed Computing in Java, John Wiley & Sons, 2004.

    2004 Java2 *.

    Whats Special in util.concurrent?Creator of util.concurrent: Doug Lea says:Whenever youre about to usenew Thread();synchronizedObject.wait, Object.notify, Object.notifyAllCheck first if theres a class thatAutomates your tasksSimplifies your building blocks

    2004 Java2 *.

    History of util.concurrent1997Concurrent Programming in Java, 1st edition

    1998Package EDU.oswego.cs.dl.util.concurrent

    1999Concurrent Programming in Java, 2nd edition

    2002JSR-166

    2004JDK 1.5 (5.0)

    2004 Java2 *.

    OutlineBefore JDK1.5ThreadRace conditionSynchronizationSince JDK 1.5Better executorFlexible lockRicher IPC facilitiesOther stuff

    2004 Java2 *.

    @ 2004.08.03.SchedulingLockBounded buffer problemFIFO (first in first out)LIFO (last in first out)

  • 1A. ThreadBasics*The world before JDK 1.5

    2004 Java2 *.

    Concurrent Programskernel

    2004 Java2 *.

    Java Threads, 1st Wayjava.langnmain

    2004 Java2 *.

    Thread Demo #1public class MyThread1 extends Thread {

    public void run() {for (int x = 0; x < 20; ++x)System.out.println(x);}

    public static void main(String[] args) {Thread[] worker = new Thread[5];for (int i = 0; i < 5; i++) worker[i] = new MyThread1();

    for (int i = 0; i < 5; i++) worker[i].start();}}MyThread1Threadmain5

    2004 Java2 *.

    01234567 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 38 4 4 49 5 5 510 6 6 611 7 7 712 8 8 8 4 5 6 7 9 9 913 10 10 1014 11 11 1115 12 12 1216 817 9 10 11 12 13 14 15 16 17 1818 13 13 1319 14 14 14 15 15 15 16 16 16 17 17 17 19 18 19 18 19 18 19

    2004 Java2 *.

    Lessons Learned: UncertaintyTime sliceWhere? In general, unknown.

    SchedulingWhen? In general, unknown.To Whom? In general, unknown.

    2004 Java2 *.

    Java Threads, 2nd WayThreadmain

    2004 Java2 *.

    Thread Demo #2public class MyThread2 implements Runnable {

    public void run() {//}

    public static void main(String[] args) {Thread[] worker = new Thread[5];for (int i = 0; i < 5; i++) worker[i] =new Thread( );

    for (int i = 0; i < 5; i++) worker[i].start();}}Threadmain interface Runnablenew MyThread2()

  • 1B. Executor*Whats new in JDK 1.5

    2004 Java2 *.

    Limitations of Java ThreadsNumber of threadsSpecified explicitlyHard to be adjusted dynamically

    Execution modelsInflexible

    2004 Java2 *.

    MyWorkermain

    2004 Java2 *.

    Thread public class ThreadDemo extends Thread {private int sn;public ThreadDemo(int sn) { this.sn = sn; }

    public void run() {// delay for a while...System.out.println(sn);}

    public static void main(String[] args) {int i = 0;for (;;) {new ThreadDemo(i).start();++i;}}}

    2004 Java2 *.

    Executor Demopublic class ExecutorDemo implements Runnable {private int sn;public ExecutorDemo(int sn) { this.sn = sn; }public void run() { /* */ }

    public static void main(String[] args) {Executor pool =Executors.newFixedThreadPool(300);// Executors.newCachedThreadPool();// Executors.newSingleThreadExecutor();

    int i = 0;for (;;) {pool.execute( new ExecutorDemo(i) );++i;}}}

    2004 Java2 *.

    Whats Special? Seeing is Believing!

    2004 Java2 *.

    Asynchronous ExecutionMyWorker

  • 2A. Race Conditionmutual execution*The world before JDK 1.5

    2004 Java2 *.

    Race Condition ()http://www.garfield.com/comics/comics_archives_strip.html?2004-ga040201

    2004 Java2 *.

    Race Condition Demopublic class Race1 extends Thread {

    // shared variableprivate static int x = 0; // counter

    public void run() {while (true) {

    System.out.println( x );++x;

    }}

    public static void main(String[] args) { /**/ }}

    2004 Java2 *.

    012...439440441 442 443 444 . . 1037 1038 1039 1040 . . 1807 1808 1809 1810 1810 1810 1810 18101810 1039 1811 1812 1813 18141815 1816 1817 1818 1819 1820

    2004 Java2 *.

    Java Memory ModelWorking memoryEvery thread has a working memory in which it keeps its own working copy of variables that it must use or assign.As the thread executes a program, it operates on these working copies.

    Master copyThe main memory contains the master copy of every variable.

    Transfer: working master copyThere are rules about when a thread is permitted or required to transfer the contents of its working copy of a variable into the master copy or vice versa.The Java Virtual Machine Specification, 2nd EditionJSR-133

    2004 Java2 *.

    Read/Write Details// shared variableprivate static int x = 0;

    System.out.println( x );

    ++x;Read( x )Write( x )

    2004 Java2 *.

    Why Race Condition?1809 Read( x )1810 Write( x )1810 Read( x )1811 Write( x )1810 Read( x )1810 Read( x )1811 Write( x )1811 Read( x )

    2004 Java2 *.

    Solution: Exclusive Executionpublic class Race2 extends Thread {

    private static int x = 0;private static Object x_lock = new Object();

    public void run() {while (true) {synchronized ( x_lock ) {System.out.println( x );++x;}}}

    public static void main(String[] args) { /**/ }}

  • 2B. Lock*Whats new in JDK 1.5

    2004 Java2 *.

    3 Ways to Use synchronizedprivate static int x = 0;

    public synchronized void f() {while (true) {++x; //}}

    public void g() {synchronized ( this ) {while (true) {++x; //}}}public void h() {while (true) {synchronized ( this ) {++x; //}}}123

    2004 Java2 *.

    JSR 166: Lock[1/2]private static int x = 0;

    public void g() {synchronized ( this ) {while (true) {++x; //}}}import java.util.concurrent.locks.*;

    private static Lock lock= new ReentrantLock();

    public void g2() {lock.lock();try {while (true) {++x; //}} finally {lock.unlock();}}24

    2004 Java2 *.

    JSR 166: Lock[2/2]private static int x = 0;

    public void h() {while (true) {synchronized (this) {++x; //}}}import java.util.concurrent.locks.*;

    private static Lock lock= new ReentrantLock();

    public void h2() {while (true) {lock.lock();try {++x; //} finally {lock.unlock();}}}35

    2004 Java2 *.

    Simple Benchmarkfor (int i = 0; i < 20; ++i) {x = 0;long start = System.nanoTime();f(); // g(), h(), g2(), h2()long period = System.nanoTime() - start;System.out.println("f(): " + period);}

    private synchronized void f() { // g(), h(), g2(), h2()while (true) {++x;if (x >= Integer.MAX_VALUE / 50) return;} // while}

    2004 Java2 *.

    2004 Java2 *.

    2004 Java2 *.

    interface LockReentrantLockReentrantReadWriteLockjava.util.concurrent.locks

  • 3A. Synchronizationordered execution*The world before JDK 1.5

    2004 Java2 *.

    Synchronization between ThreadsBounded buffer problemAlso known as producer-consumer problemFIFO queueboundary condition

    2004 Java2 *.

    Nave Solution: put()class BoundedBuffer {private String[] buf;private int in = -1, out = -1;private int count = 0;

    public BoundedBuffer(int size) { buf = new String[size]; }

    public void put(String s) {while (count >= buf.length); // full

    synchronized (this) {++count;buf[++in % buf.length] = s;System.out.println("--> " + s);}}

    2004 Java2 *.

    Nave Solution: get()

    public String get() {

    while (count == 0); // empty

    synchronized (this) {--count;String s = buf[++out % buf.length];System.out.println(" " + s);

    notify();}

    2004 Java2 *.

    Right Solution: get()

    public synchronized String get() {

    while (count == 0)try{ wait(); } catch(InterruptedException e) { }

    --count;String s = buf[++out % buf.length];System.out.println("

  • 3B. IPC Facilities*Whats new in JDK 1.5

    2004 Java2 *.

    Java monitor isnt pure MONITORDifference: condition variable!Java: only one (usually unnamed and hidden) condition variable per monitornotify(): wakeup one candidate (usually miss the true target) notifyAll(): wakeup all candidates (usually too coarse-grained)

    Pure monitor: n named condition variablesFiner-grained and true wakeup candidates

    2004 Java2 *.

    100% Monitor Solution:put()class BoundedBuffer {Lock lock = new ReentrantLock(); // mutual exclusion

    Condition notFull = lock.newCondition();Condition notEmpty = lock.newCondition();

    public void put(String s) {lock.lock();try {while (count >= buf.length) notFull.await();catch (InterruptedException e) {}// buffer manipulationnotEmpty.signal();} finally { lock.unlock(); }}try { }

    2004 Java2 *.

    100% Monitor Solution:get()// Condition notFull = lock.newCondition();// Condition notEmpty = lock.newCondition();

    public String get() {lock.lock();try {while (count == 0) notEmpty.await();catch (InterruptedException e) {}// buffer manipulation

    notFull.signal();return s;} finally { lock.unlock(); }}try { }

    2004 Java2 *.

    Other IPC FacilitiesSemaphoreCyclicBarrierExchangerCountDownLatch

  • 4. Misc*Whats new in JDK 1.5

    2004 Java2 *.

    Topics not Covered in this TalkConcurrent containersjava.util.concurrentArrayBlockingQueueConcurrentHashMapCopyOnWriteArrayList

    Atomic scalarsjava.util.concurrent.atomicAtomicLongAtomicIntegerArray

    2004 Java2 *.

    Recommended ReadingsJSR 166Concurrency JSR-166 Interest Sitehttp://gee.cs.oswego.edu/dl/concurrency-interest/Rationale behind JSR-166Doug Lea, Concurrent Programming in Java--Design Principles and Patterns, 2nd edition, Addison-Wesley, 1999.Concurrent programming conceptsAbraham Silberschatz et. al, Operating System Concepts, 6th edition, John Wiely & Sons, 2003.Andrew S. Tanenbaum, Modern Operating Systems, 2nd edition, Prentice Hall, 2001.http://william.cswiz.org/present/20040803-javatwo

    2004 Java2 *.

    JDK 1.5 Doug Lea wait/notify/notifyAllsynchronizedThread java.util.concurrent

    1998 1.0 JSR 166 JDK 1.5

    Java

    *

    *

    44 / 562 = 7.83%Ken Arnold, James Gosling, David Holmes, The Java Programming Language, 3rd edition, Addison-Wesley, 2000.Chapter 10.

    51 / 534 = 9.55%Mary Campione, Kathy Walrath, Alison Huml, The Java Tutorial, 3rd edition, Addison-Wesley, 2000.Chapter 8, Appendix D.

    78 / 1090 = 7.16%Bruce Eckel, Thinking in Java, 3rd edition, Prentice Hall, 2002.Chapter 14.

    46 / 244 = 18.85%Peter Haggar, Practical Java Programming Language Guide, Addison-Wesley, 2000.Praxis 34, 46 58.

    24 / 232 = 10.34%Joshua Bloch, Effective Java Programming Language Guide, Addison-Wesley, 2001.Item 48 53.

    137 / 867 = 15.80%

    Abraham Silberschatz et. al, Operating System Concepts, 6th edition, John Wiely & Sons, 2003.Chapters 4, 5, 7, 8.

    153 / 934 = 16.38%Andrew S. Tanenbaum, Modern Operating Systems, 2nd edition, Prentice Hall, 2001.Chapters 2, 3, 10, 11.