24slide (1)

Upload: arun-kumar

Post on 06-Apr-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 24slide (1)

    1/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    1

    Chapter 24 Multithreading

    Chapter 25 Networking

    Chapter 24 Multithreading

    Chapter 16 Applets and Multimedia

    Chapter 26 Internationalization

    Chapter 16 Applets and Multimedia

    Chapter 18 Binary I/O

  • 8/3/2019 24slide (1)

    2/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    2

    Objectives To understand the concept of multithreading and apply it to develop animation (24.2).

    To develop task classes by implementing the Runnable interface in cases of multipleinheritance (24.4).

    To create threads to run tasks using the Thread class (24.3).

    To control animations using threads (24.5, 24.7).

    To run code in the event dispatcher thread (24.6) .

    To execute tasks in a thread pool (24.8).

    To use synchronized methods or block to synchronize threads to avoid race conditions(24.7.1).

    To synchronize threads using locks (24.10) .

    To facilitate thread communications using conditions on locks (24.11-24.12).

    To use blocking queues to synchronize access to an array queue, linked queue, andpriority queue (24.13 Optional).

    To restrict number of accesses to a shared resource using semaphores (24.14 Optional).

    To use the resource ordering technique to avoid deadlock (24.7.4). To understand the life cycle of a thread (24.16).

    To create synchronized collections using the static methods in the Collections class(24.17).

    To display the completion status of a task using JProgressBar (24.18 Optional).

  • 8/3/2019 24slide (1)

    3/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    3

    Threads Concept

    Multiple

    threads on

    multiple

    CPUs

    Multiple

    threads

    sharing a

    single CPU

    Thread 3

    Thread 2

    Thread 1

    Thread 3

    Thread 2

    Thread 1

  • 8/3/2019 24slide (1)

    4/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    4

    Creating Tasks and Threads

    // Custom task classpublic class TaskClass implements Runnable {

    ...public TaskClass(...) {...

    }

    // Implement the run method in Runnablepublic void run() {// Tell system how to run custom thread...

    }...

    }

    // Client classpublic class Client {

    ...public void someMethod() {...// Create an instance of TaskClassTaskClass task = new TaskClass(...);

    // Create a threadThread thread = new Thread(task);

    // Start a threadthread.start();...

    }...

    }

    java.lang.Runnable TaskClass

  • 8/3/2019 24slide (1)

    5/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    5

    Example:

    Using the Runnabel Interface toCreate and Launch Threads

    Objective: Create and run three threads:

    The first thread prints the lettera 100 times.

    The second thread prints the letterb 100

    times.

    The third thread prints the integers 1 through100.

    TaskThreadDemo Run

  • 8/3/2019 24slide (1)

    6/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    6

    The Thread Class

    java.lang.Thread

    +Thread()

    +Thread(task: Runnable)

    +start(): void

    +isAlive(): boolean

    +setPriority(p: int): void

    +join(): void

    +sleep(millis: long): void

    +yield(): void

    +interrupt(): void

    Creates a default thread.

    Creates a thread for a specified task.

    Starts the thread that causes the run() method to be invoked by the JVM.

    Tests whether the thread is currently running.

    Sets priority p (ranging from 1 to 10) for this thread.

    Waits for this thread to finish.

    Puts the runnable object to sleep for a specified time in milliseconds.

    Causes this thread to temporarily pause and allow other threads to execute.

    Interrupts this thread.

    interfacejava.lang.Runnable

  • 8/3/2019 24slide (1)

    7/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    7

    Thread States A thread can be in one of Four states for threads: new,

    runnable, blocked, dead

    newstart

    dead

    Note: suspend, resume,

    stop deprecated.

    runnable

    run exits

    stop

    blocked

    sleep

    done sleeping

    suspendresume

    await signal

    blockon I/O

    I/O complete

    Wait for lock

    Lock available

  • 8/3/2019 24slide (1)

    8/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    8

    Thread States When a thread has just been created using the new operator, it is in

    the new state.

    Once start method is invoked (which calls the run method), thethread becomes runnable.

    A runnable thread might not be running. There can be many runnable threads. But only one of them can be

    running at any time point.

    OS decides which thread to run. More on this later.

    new

    runnable

    start

  • 8/3/2019 24slide (1)

    9/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    9

    Thread States A runnable thread enters the blocked state when

    1. The thread is currently running and method Thread.sleep is called

    2. suspendmethod of the thread is called. (deprecated)

    3. The thread calls the await method.

    4. The thread tries to lock an object locked by another thread.

    5. The thread calls an operation that is blocked on i/o.

    runnable

    blocked

    sleep

    suspend

    await

    blockon I/O

    Wait for lockA blocked

    thread cannot

    be running

  • 8/3/2019 24slide (1)

    10/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    10

    Thread States A blocked reenters runnable state when

    1. It has slept the specified amount of time.

    2. resume method of the thread is called. (deprecated)

    3. Another method calls signal or signalAll

    4. Object lock released by other thread

    5. I/O completed.

    runnable

    blockeddone sleeping

    resume

    signal

    I/O completeLock available

  • 8/3/2019 24slide (1)

    11/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    11

    Thread States

    A runnable thread enters the dead state when Its run method exits. Natural death.

    stop method of the thread is called. (deprecated)

    An exception is thrown but not caught.

    dead

    runnable

    run exits

    stop

  • 8/3/2019 24slide (1)

    12/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    12

    Thread States Finding out states of threads

    Method isAlive allows you to find out whether

    a thread is alive or dead.

    This method returns t

    ru

    e if the thread is runnable orblocked,

    false if the thread is still new and not yet runnable or

    if the thread is dead

    No way to find out whether an alive thread isrunning, runnable, or blocked.

  • 8/3/2019 24slide (1)

    13/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    13

    The Static yield() Method

    You can use the yield() method to temporarily release timefor other threads. For example, suppose you modify thecode in Lines 57-58 in TaskThreadDemo.java as follows:

    public void run() {

    for (int i = 1; i

  • 8/3/2019 24slide (1)

    14/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    14

    The Static sleep(milliseconds) Method

    The sleep(long mills) method puts the thread to sleep for the specified

    time in milliseconds. For example, suppose you modify the code inLines 56-60 in TaskThreadDemo.java as follows:

    public void run() {for (int i = 1; i = 50) Thread.sleep(1);

    }catch (InterruptedException ex) {}

    }}

    Every time a number (>= 50) is printed, the print100 thread is put tosleep for 1 millisecond.

  • 8/3/2019 24slide (1)

    15/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    15

    sleep vs. yieldThere is a big difference

    Calling sleep put the current running thread intothe blocked state

    Calling yield does not put the calling thread, t1into the blocked state

    It merely let the scheduler kick in and pickanother thread to run.

    It might happen that the t1 is select to run again.T

    his happens when t1 has a higher priority thanall other runnable threads.

  • 8/3/2019 24slide (1)

    16/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    16

    The join() MethodYou can use the join() method to force one thread to wait for another thread to

    finish. For example, suppose you modify the code in Lines 56-60 inTaskThreadDemo.java as follows:

    public void run(){Thread thread4 = new Thread(new PrintChar('c', 60));

    thread4.start();

    try {for (int i = 1; i < lastNum; i++){

    System.out.print(" " + i);

    if (i == 50) thread4.join();}

    }catch (InterruptedException ex) {

    }}

    The numbers after 50 are printed after thread4 is finished.

  • 8/3/2019 24slide (1)

    17/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    17

    isAlive(), interrupt(), and isInterrupted()

    The isAlive() method is used to find out the state of athread. It returns true if a thread is in the Ready, Blocked,or Running state; it returns false if a thread is new and hasnot started or if it is finished.

    The interrupt() method interrupts a thread in the followingway: If a thread is currently in the Ready or Running state,its interrupted flag is set; if a thread is currently blocked, itis awakened and enters the Ready state, and an

    java.io.InterruptedException is thrown.

    The isInterrupt() method tests whether the thread isinterrupted.

  • 8/3/2019 24slide (1)

    18/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    18

    Outline Introduction: Why and what

    Basics: creating and running threads

    Issues

    T

    hread statesThread scheduling

    Synchronization

    Suspending and stopping threads

    Uses

    Animation

    Threads and Swing

  • 8/3/2019 24slide (1)

    19/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    19

    Thread SchedulingAt any time, there might be many runnable threads. But only one of

    them is actually running.

    The thread scheduler decides which runnable thread to run.

    Questions:

    When does the thread scheduler kick in and pick a thread to run?

    How does the thread scheduler select among the runnable

    threads?A not-so-precise answer:

    A running Java thread will continue to run until

    It calls yield method, or

    It ceases to be runnable (dead or blocked), or

    Another thread with higher priority moves out of blockedstate

    Then the thread scheduler kicks in andpicks another thread withthe highest priority to run

  • 8/3/2019 24slide (1)

    20/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    20

    Thread Scheduling Two different thread implementations

    Native thread implementation (e.g. Windows):

    Performs time-slicing. Interrupts the running

    thread periodically to give other threads achance to run.

    Green thread implementation (e.g. Solaris)

    Does not perform time-slicing. It keeps a

    running thread active until a higher-prioritythread awakes and takes control.

  • 8/3/2019 24slide (1)

    21/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    21

    Thread SchedulingThe answer on slide 19 is precise for the green thread

    implementation.

    For the native thread implementation, the precise answer is

    A running Java thread will continue to run untilIt calls yield method, or

    It ceases to be runnable (dead or blocked), or

    Another thread with higher priority moves out of blocked

    state, or

    It is pre-emptied by OS (time-slicing).

    Then the thread scheduler kicks in and picks another thread

    with the highest priority to run

  • 8/3/2019 24slide (1)

    22/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    22

    Thread Priority

    Each thread is assigned a default priority of

    Thread.NORM_PRIORITY. You can reset the

    priority using setPriority(int priority).

    Some constants for priorities include

    Thread.MIN_PRIORITY

    Thread.MAX_PRIORITYThread.NORM_PRIORITY

  • 8/3/2019 24slide (1)

    23/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    23

    Example: Flashing Text

    FlashingText Run

  • 8/3/2019 24slide (1)

    24/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    24

    GUI Event DispatcherThread

    GUI event handling and painting code executes in asingle thread, called the event dispatcher thread. This

    ensures that each event handler finishes executing before

    the next one executes and the painting isnt interrupted by

    events.

  • 8/3/2019 24slide (1)

    25/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    25

    invokeLater and invokeAndWait

    In certain situations, you need to run the code in the eventdispatcher thread to avoid possible deadlock. You can use the

    static methods, invokeLater and invokeAndWait, in the

    javax.swing.SwingUtilities class to run the code in the event

    dispatcher thread. You must put this code in the run method of aRunnable object and specify the Runnable object as the

    argument to invokeLater and invokeAndWait. The invokeLater

    method returns immediately, without waiting for the event

    dispatcher thread to execute the code.T

    he invokeAndWaitmethod is just like invokeLater, except that invokeAndWait

    doesn't return until the event-dispatching thread has executed the

    specified code.

  • 8/3/2019 24slide (1)

    26/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    26

    Launch Application from Main MethodSo far, you have launched your GUI application from the

    main method by creating a frame and making it visible. Thisworks fine for most applications. In certain situations,

    however, it could cause problems. To avoid possible thread

    deadlock, you should launch GUI creation from the event

    dispatcher thread as follows:public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

    public void run() {

    // Place the code for creating a frame and setting it properties

    }

    });

    }EventDispatcherThreadDemo Run

  • 8/3/2019 24slide (1)

    27/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    27

    Case Study: Clock with Audio (Optional)

    The example creates an applet that displays a running clock and

    announces the time at one-minute intervals. For example, if the

    current time is 6:30:00, the applet announces, "six oclock thirty

    minutes a.m." If the current time is 20:20:00, the applet announces,

    "eight oclock twenty minutes p.m." Also add a label to display thedigital time.

    ClockWithAudio Run

  • 8/3/2019 24slide (1)

    28/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    28

    Run Audio on Separate Thread

    When you run the preceding program, you will notice that the secondhand does not display at the first, second, and third seconds of the

    minute. This is because sleep(1500) is invoked twice in the

    announceTime() method, which takes three seconds to announce the

    time at the beginning of each minute. Thus, the next action event is

    delayed for three seconds during the first three seconds of eachminute. As a result of this delay, the time is not updated and the clock

    was not repainted for these three seconds. To fix this problem, you

    should announce the time on a separate thread. This can be

    accomplished by modifying the announceTime method.

    ClockWithAudioOnSeparateThread Run

  • 8/3/2019 24slide (1)

    29/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    29

    Thread Pools

    Starting a new thread for each task could limit throughput and cause

    poor performance. A thread pool is ideal to manage the number oftasks executing concurrently. JDK 1.5 uses the Executor interface for

    executing tasks in a thread pool and the ExecutorService interface for

    managing and controlling tasks. ExecutorService is a subinterface of

    Executor.

    Shuts down the executor, but allows the tasks in the executor to

    complete. Once shutdown, it cannot accept new tasks.

    Shuts down the executor immediately even though there are

    unfinished threads in the pool. Returns a list of unfinished

    tasks.

    Returns true if the executor has been shutdown.

    Returns true if all tasks in the pool are terminated.

    interfacejava.util.concurrent.Executor

    +execute(Runnable object): void Executes the runnable task.

    interfacejava.util.concurrent.ExecutorService

    +shutdown(): void

    +shutdownNow(): List

    +isShutdown(): boolean

    +isTerminated(): boolean

  • 8/3/2019 24slide (1)

    30/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    30

    Creating Executors

    To create an Executor object, use the static methods in the Executors

    class.

    Creates a thread pool with a fixed number of threads executingconcurrently. A thread may be reused to execute another task

    after its current task is finished.

    Creates a thread pool that creates new threads as needed, butwill reuse previously constructed threads when they areavailable.

    java.util.concurrent.Executors

    +newFixedThreadPool(numberOfThreads:

    int): ExecutorService

    +newCachedThreadPool():

    ExecutorService

    ExecutorDemo Run

  • 8/3/2019 24slide (1)

    31/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    31

    Thread Synchronization

    A shared resource may be corrupted if it is

    accessed simultaneously by multiple threads. For

    example, two unsynchronized threads accessingthe same bank account may cause conflict.

    Step balance thread[i] thread[j]

    1 0 newBalance = bank.getBalance() + 1;

    2 0 newBalance = bank.getBalance() + 1;

    3 1 bank.setBalance(newBalance);

    4 1 bank.setBalance(newBalance);

  • 8/3/2019 24slide (1)

    32/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    32

    Example: Showing Resource Conflict

    Objective: Write a program that demonstrates the problem ofresource conflict. Suppose that you create and launch onehundred threads, each of which adds a penny to an account.Assume that the account is initially empty.

    AccountWithoutSync

    Run

    Account

    -balance: int

    +getBalance(): int

    +deposit(amount: int): void

    100AccountWithoutSync

    -bank: Account-thread: Thread[]

    +main(args: String[]): void

    AddAPennyTask

    +run(): void

    java.lang.Runnable

    1 11

  • 8/3/2019 24slide (1)

    33/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    33

    Race ConditionWhat, then, caused the error in the example? Here is a possible scenario:

    The effect of this scenario is that Task 1 did nothing, because inStep 4 Task 2 overrides Task 1's result. Obviously, the problem isthat Task 1 and Task 2 are accessing a common resource in a way

    that causes conflict. This is a common problem known as a racecondition in multithreaded programs. A class is said to be thread-

    safe if an object of the class does not cause a race condition in thepresence of multiple threads. As demonstrated in the precedingexample, the Account class is not thread-safe.

    Step balance Task 1 Task 2

    1 0 newBalance = balance + 1;

    2 0 newBalance = balance + 1;

    3 1 balance = newBalance;

    4 1 balance = newBalance;

  • 8/3/2019 24slide (1)

    34/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    34

    The synchronized keywordTo avoid resource conflicts, it is necessary to prevent more than one

    thread from simultaneously entering certain part of the program,known as critical region. The critical region in the Listing 24.7 is the

    entire deposit method. You can use the synchronized keyword to

    synchronize the method so that only one thread can access the method

    at a time. There are several ways to correct the problem in Listing

    24.7, one approach is to make Account thread-safe by adding the

    synchronized keyword in the deposit method in Line 45 as follows:

    public synchronized void deposit(double amount)

  • 8/3/2019 24slide (1)

    35/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    35

    Synchronizing Instance Methods and

    Static Methods

    A synchronized method acquires a lock before it executes.In the case of an instance method, the lock is on the objectfor which the method was invoked. In the case of a staticmethod, the lock is on the class. If one thread invokes a

    synchronized instance method (respectively, static method)on an object, the lock of that object (respectively, class) isacquired first, then the method is executed, and finally thelock is released. Another thread invoking the same method

    of that object (respectively, class) is blocked until the lockis released.

  • 8/3/2019 24slide (1)

    36/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    36

    Synchronizing Instance Methods and

    Static Methods

    With the deposit method synchronized, the preceding scenario cannot

    happen. IfTask 2 starts to enter the method, and Task 1 is already in

    the method, Task 2 is blocked until Task 1 finishes the method.

    Acquire a lock on the object account

    Execute the deposit method

    Release the lock

    Task 1

    Acqurie a lock on the object account

    Execute the deposit method

    Release the lock

    Task 2

    Wait to acquire the lock

  • 8/3/2019 24slide (1)

    37/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    37

    Synchronizing Statements

    Invoking a synchronized instance method of an object acquires a lock

    on the object, and invoking a synchronized static method of a classacquires a lock on the class. A synchronized statement can be used toacquire a lock on any object, not just this object, when executing a

    block of the code in a method. This block is referred to as asynchronized block. The general form of a synchronized statement is

    as follows:

    synchronized (expr) {statements;

    }

    The expression expr must evaluate to an object reference. If the objectis already locked by another thread, the thread is blocked until thelock is released. When a lock is obtained on the object, the statementsin the synchronized block are executed, and then the lock is released.

  • 8/3/2019 24slide (1)

    38/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    38

    Synchronizing Statements vs. Methods

    Any synchronized instance method can be converted into a

    synchronized statement. Suppose that the following is a synchronized

    instance method:

    public synchronized void xMethod() {

    // method body}

    This method is equivalent to

    public void xMethod() {synchronized (this) {

    // method body}

    }

  • 8/3/2019 24slide (1)

    39/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    39

    Synchronization Using LocksA synchronized instance method implicitly acquires a lock on the

    instance before it executes the method.JDK 1.5 enables you to use locks explicitly. The new locking featuresare flexible and give you more control for coordinating threads. Alock is an instance of the Lockinterface, which declares the methodsfor acquiring and releasing locks, as shown in Figure below. A lockmay also use the newCondition() method to create any number of

    Condition objects, which can be used for thread communications.

    Same as ReentrantLock(false).

    Creates a lock with the given fairness policy. When thefairness is true, the longest-waiting thread will get the

    lock. Otherwise, there is no particular access order.

    interfacejava.util.concurrent.locks.Lock

    +lock(): void

    +unlock(): void

    +newCondition(): Condition

    Acquires the lock.

    Releases the lock.

    Returns a new Condition instance that is bound to this

    Lock instance.

    java.util.concurrent.locks.ReentrantLock

    +ReentrantLock()

    +ReentrantLock(fair: boolean)

  • 8/3/2019 24slide (1)

    40/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    40

    Fairness Policy

    ReentrantLock is a concrete implementation of Lock forcreating mutual exclusive locks. You can create a lock withthe specified fairness policy. True fairness policiesguarantee the longest-wait thread to obtain the lock first.False fairness policies grant a lock to a waiting thread

    without any access order. Programs using fair locksaccessed by many threads may have poor overallperformance than those using the default setting, but havesmaller variances in times to obtain locks and guaranteelack of starvation.

  • 8/3/2019 24slide (1)

    41/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    41

    Example: Using Locks

    This example revises AccountWithoutSync.java in Listing24.7 to synchronize the account modification using explicit

    locks.

    AccountWithSyncUsingLock

    Run

  • 8/3/2019 24slide (1)

    42/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    42

    Cooperation Among Threads

    The conditions can be used to facilitate communications among

    threads. A thread can specify what to do under a certain condition.Conditions are objects created by invoking the newCondition()method on a Lock object. Once a condition is created, you can use itsawait(), signal(), and signalAll() methods for thread communications,as shown in Figure below. The await() method causes the currentthread to wait until the condition is signaled. The signal() method

    wakes up one waiting thread, and the signalAll() method wakes allwaiting threads.

    interface

    java.util.concurrent.Condition+await(): void

    +signal(): void

    +signalAll(): Condition

    Causes the current thread to wait until the condition is signaled.

    Wakes up one waiting thread.

    Wakes up all waiting threads.

  • 8/3/2019 24slide (1)

    43/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    43

    Example: Thread Cooperation

    Write a program that demonstrates thread cooperation. Suppose that

    you create and launch two threads, one deposits to an account, andthe other withdraws from the same account. The second thread has to

    wait if the amount to be withdrawn is more than the current balance

    in the account. Whenever new fund is deposited to the account, the

    first thread notifies the second thread to resume. If the amount is still

    not enough for a withdrawal, the second thread has to continue to

    wait for more fund in the account. Assume the initial balance is 0 and

    the amount to deposit and to withdraw is randomly generated.

    ThreadCooperation

    Run

  • 8/3/2019 24slide (1)

    44/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    44

    Cooperation Among Threads

    To synchronize the operations, use a lock with a condition:

    newDeposit (i.e., new deposit added to the account). If the balance isless than the amount to be withdrawn, the withdraw task will waitfor the newDeposit condition. When the deposit task adds money tothe account, the task signals the waiting withdraw task to try again.The interaction between the two tasks is shown in Figure below.

    while (balance < withdrawAmount)

    newDeposit.await();

    Withdraw Task

    balance -= withdrawAmount

    lock.unlock();

    Deposit Task

    lock.lock();

    newDeposit.signalAll();

    balance += depositAmount

    lock.unlock();

    lock.lock();

  • 8/3/2019 24slide (1)

    45/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    45

    Condition ObjectOften, a thread enters a critical section, only to discover that it

    cant proceed until a condition is fulfilled. JDK5.0 uses a conditionobject to manage threads that have acquired a lock but cannot douseful work.

    For example, what do we do where there is not enough money inthe account? We wait until some other thread has added funds. But

    this thread has just gained exclusive access to the lock, so no otherthread has a chance to make a deposit. This is where conditionobject come in.

    A lock object can have one or more associated condition objects.You obtain a condition object with the newCondition method. It

    is customary to give each condition object a name that evokes thecondition that it represents. For example:

    Condition newDeposit = lock.newCondition();

    di i bj

  • 8/3/2019 24slide (1)

    46/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    46

    Condition ObjectIf the transfer method finds that sufficient funds are not available, it

    calls newDeposit.await();

    The current thread is now blocked and gives up the lock. This lets inanother thread that can (possibly) increase the account balance.

    When another thread transfers money, it should call

    newDeposit.signalAll();

    to unblock all threads that are waiting for the condition.

    orcallnewDeposit.signa();

    to unblock a single thread from the wait set, chosen at random.

    When the threads are removed from the wait set, they are againrunnable and the scheduler will eventually activate them again.At that time, they will attempt to reenter the object. As soon as

    the lock is available, one of them will acquire the lock andcontinue where it left off, returning from the await. At this timethe thread should test the condition again. There is no guaranteethat the condition is now fulfilled.

  • 8/3/2019 24slide (1)

    47/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    47

    Condition Object

    It is crucial that some other thread calls the signalAll

    eventually. When a thread calls await, it has no way of

    unblocking itself. It puts its faith in the other thread. If none of

    them bother to unblock the waiting thread, it will never run again.

    This can lead to deadlocksituation.

  • 8/3/2019 24slide (1)

    48/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    48

    Case Study: Producer/ConsumerConsider the classic Consumer/Producer example. Suppose you use a buffer tostore integers. The buffer size is limited. The buffer provides the method write(int)

    to add an int value to the buffer and the method read() to read and delete an intvalue from the buffer. To synchronize the operations, use a lock with twoconditions: notEmpty (i.e., buffer is not empty) and notFull (i.e., buffer is not full).When a task adds an int to the buffer, if the buffer is full, the task will wait for thenotFull condition. When a task deletes an int from the buffer, if the buffer is empty,the task will wait for the notEmpty condition. The interaction between the twotasks is shown in Figure below.

    while (count == CAPACITY)notFull.await();

    Task for adding an int

    Add an int to the buffer

    notEmpty.signal();

    while (count == 0)notEmpty.await();

    Task for deleting an int

    Delete an int to the buffer

    notFull.signal();

  • 8/3/2019 24slide (1)

    49/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    49

    Case Study: Producer/Consumer (Optional)

    Listing 24.10 presents the complete program. The program contains

    the Buffer class (lines 43-89) and two tasks for repeatedly producingand consuming numbers to and from the buffer (lines 15-41). Thewrite(int) method (line 58) adds an integer to the buffer. The read()method (line 75) deletes and returns an integer from the buffer.

    For simplicity, the buffer is implemented using a linked list (lines 48-49). Two conditions notEmpty and notFull on the lock are created inlines 55-56. The conditions are bound to a lock. A lock must beacquired before a condition can be applied.

    ConsumerProducer Run

  • 8/3/2019 24slide (1)

    50/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    50

    Deadlock

    The Dining-Philosophers Problem

  • 8/3/2019 24slide (1)

    51/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. Allrights reserved. 0-13-148952-6

    51

    DeadlockSometimes two or more threads need to acquire the locks on several shared objects.

    This could cause deadlock, in which each thread has the lock on one of the objectsand is waiting for the lock on the other object. Consider the scenario with two

    threads and two objects, as shown in Figure below. Thread 1 acquired a lock on

    object1 and Thread 2 acquired a lock on object2. Now Thread 1 is waiting for the

    lock on object2 and Thread 2 for the lock on object1. The two threads wait for each

    other to release the in order to get the lock, and neither can continue to run.

    synchronized (object1) {

    // do something here

    synchronized (object2) {

    // do something here

    }

    }

    Thread 1

    synchronized (object2) {

    // do something here

    synchronized (object1) {// do something here

    }

    }

    Thread 2Step

    1

    2

    3

    4

    5

    6

    Wait forThread 2 torelease the lock on object2

    Wait forThread 1 to

    release the lock on object1

  • 8/3/2019 24slide (1)

    52/52

    Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All 52

    Preventing Deadlock

    Deadlock can be easily avoided by using a simple technique known

    as resource ordering. With this technique, you assign an order on allthe objects whose locks must be acquired and ensure that eachthread acquires the locks in that order. For the example in Figure inlast slide, suppose the objects are ordered as object1 and object2.Using the resource ordering technique, Thread 2 must acquire a lock

    on object1 first, then on object2. Once Thread 1 acquired a lock onobject1, Thread 2 has to wait for a lock on object1. So Thread 1 will

    be able to acquire a lock on object2 and no deadlock would occur.