IsAlive() and Join() by Kamalakar Dandu

Embed Size (px)

Citation preview

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    1/13

    isAlive() and join()

    Often we want the main thread to finish last, thisis accomplished by calling sleep() within main(),with a long enough delay to ensure that all childthreads terminate prior to the main thread.

    However, this is hardly a satisfactory solution, andit also raise a larger question: how can one threadknow when another thread has ended?

    Thread provides a means by which you cananswer this question.two ways exist to determinewhether a thread has finished, isAlive() or join()method.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    2/13

    To determine whether a thread has finished, you can call

    isAlive() on the thread. This method is defined by Thread,

    and its general form is shown here:

    final boolean isAlive() The isAlive() method returns true if the thread upon which

    it is called is still running, otherwise it returns false.

    While isAlive() is occasionally useful, the method that you

    will more commonly use to wait for a thread to finish iscalled join(), shown here:

    final void join() throws InterruptedException

    This method waits until the thread on which it is called

    terminates. Its name come from the concept of the callingthread waiting until the specified thread joins it.

    Addition form of join() allow you to specify a maximum

    amount of time that you want to wait for the specified

    thread terminate.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    3/13

    Synchronization

    When two or more threads need access to the sharedresource, they need some way to ensure that the resource

    will be used by only one thread at a time. The process by

    which this is achieved is calledsynchronization. Java

    provides unique, language-level support for it.

    Key to synchronization is the concept of the monitor. A

    monitor is an object that is used as a mutually exclusive

    lock. Only one thread can own a monitor at a given time.

    When a thread acquires a lock, it is said to have entered the

    monitor. All other threads attempting to enter the locked monitor

    will be suspended until the first thread exits the

    monitor.These other threads are said to be waiting for the

    monitor.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    4/13

    If you have worked with synchronization whenusing other languages, such as C or C++, youknow that it can be a bit tricky to use. This isbecause most languages do not, themselves,support synchronization. Instead, to synchronizethreads, your programs need to utilize operating

    system primitives. Fortunately, because Javaimplements synchronization through languageelements, most of the complexity associated withsynchronization has been eliminated. You can

    synchronize your code in either of two ways. Bothinvolve the use of thesynchronizedkeyword.

    Using Synchronized methods

    The synchronized Statement

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    5/13

    Using Synchronized Methods

    Synchronization is easy in Java, because allobjects have their own implicit monitor associatedwith them. To enter an objects monitor, just call amethod that has been modify with the

    synchronizedkeyword.

    While a thread is inside a synchronized method,all other threads that try to call it on the sameinstance have to wait. To exit the monitor and passcontrol of the object to the next waiting thread, theowner of the monitor simply returns from thesynchronized method.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    6/13

    To understand the need for synchronization, lets

    begin with a simple example.

    The following program has three simple class

    Callme, Caller and Synch.

    The first one, Call me, has a single method named

    call(). The call method takes a String parametercalled msg. This method tries to print the msg

    string inside of square brackets. The interesting

    thing to notice is that after call() prints the opening

    bracket and the msg string, it callsThread.sleep(1000), which pause the current

    thread for a second.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    7/13

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    8/13

    As you can see by calling sleep(), the call()method allows execution to switch to another

    thread. This results in the mixed-up output of thethree message strings. Inthis program, nothingexists to stop all three threads from calling thesame method, on the same object, at the sametime. This is known as arace condition,becausethe three threas are racing each other to completethe method. This example used sleep() to make theeffects repeatable and obvious. In most situations,a race condition is more subtle and less

    predictable, because you can not be sure when thecontext switch will occur. This can cause aprogram to run right one one time and wrong thenext.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    9/13

    To fix the preceding program, you must serialize access tocall(). That is , you must restrict its access to only onethread at a time. To do this, you simply need to precede

    call()s defination with the keyword synchronized, asshown here:

    class Callme{synchronized void call(String msg)

    {-------;

    }}

    This prevents other threads from entering call() whileanother thread is using it. After synchronized has beenadded to call(), the output of the program is as follows:

    [Hello][Synchronized]

    [World]

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    10/13

    The synchronized Statement

    While creating synchronized methods within classesthat you create is an easy and effective means ofachieving synchronization, it will not work in all

    cases. To understand why, consider the following.Imagine that you want to synchronize access toobjects of a class that was not designed formultithreaded access. That is, the class does not use

    synchronizedmethods. Further the was not created by you, but by a third

    party, and you do not have access to the sourcecode. Thus, you cant add Synchronized to the

    appropriate methods within the class.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    11/13

    How can access to an object of this class be synchronized?Fortunately, the solution to this problem is quite easy: Yousimply put calls to the methods defined by this class inside asynchronizedblock.

    This is the general form of thesynchronizedstatement.Synchronized(object)

    {//statements to be synchronized

    }

    Here object is a reference to the object being synchronized. Asynchronized block ensures that a call to a method that is amember of object occures only after the current thread hassuccessfully entered objectss monitor.

    In previous program do the following changes

    public void run(){

    synchronized(target){

    target.call(mag);}

    }

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    12/13

    Intetthread Communication

    As discussed earlier, multithreading replaces event loop

    programming by dividing your tasks into discrete, logical units.Threads also provide a secondary benefit: they do away withpooling. Pooling is usually implemented by a loop that is used tocheck some condition repeatedly.Once the condition is true,appropriate action is taken. This waste CPU time.

    For example, consider the classic queuing problem, where onethread is producing some data and another is consuming it. Tomake the problem more interesting, suppose that the producerhas to wait until the consumer is finished before it generatesmore data.

    In a pooling system, the consumer would waste many CPUcycles while it waited for the producer to produce. Once theproducer was finished, it would start pooling, wasting more cpucycles waiting for the consumer to finished, and so on. Clearlythis situation is undesirable.

  • 8/2/2019 IsAlive() and Join() by Kamalakar Dandu

    13/13

    To avoid pooling, Java includes an interprocess communicationmechanism via the wait(), notify(), and notifyAll()methods.these methods are implemented as final methods in

    Object class, so all classes have them. All three mathods can becalled only from within asynchronized context.

    These methods are declared within Object, as shown here:final void wait() throws InterruptedExceptionfinal void notify()

    final void notifyAll() Addition forms of wait() exist that allow you to specify a peroid

    of time to wait.

    wait() tells the calling thread to give up the monitor and go tosleep until some other thread enters the same monitor and calls

    notify(). notify() wakes up a thread that called wait() on the same object.

    notifyAll() wakes up all the threads that called wait() on thesame object. One of the threads will be granted access.