Saturday, October 1, 2011

Java Thread


Introduction to Threads

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

This approach of creating a thread by implementing the Runnable Interface must be used whenever the class being used to instantiate the thread object is required to extend some other class.

Multithreading has several advantages over Multiprocessing such as;
  • Threads are lightweight compared to process
  • Threads share the same address space and therefore can share both data and code
  • Context switching between threads is usually less expensive than between processes
  • Cost of thread intercommunication is relatively low that that of process intercommunication
  • Threads allow different tasks to be performed concurrently.
Methods of the Object and Thread Class.

Object: notify,notifyAll(),wait()
Thread:-sleep(),yield()

Thread Creation
There are two ways to create thread in java;
  • Implement the Runnable interface (java.lang.Runnable)
  • By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface




The Runnable Interface Signature
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.

Extending Thread Class

The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
  • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
Synchronization:-

With respect to multithreading,Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.
In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwisel lead to dirty reads and significant errors.
Generally critical sections of the code are usually marked with synchronized keyword.
example of using Thread Synchronization is in “The Producer/Consumer Model”. 

Locks:-are used to synchronize access to a shared resource. A lock can be associated with a shared resource.Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.A lock thus implements mutual exclusion.The object lock mechanism enforces the following rules of synchronization:

A thread must acquire the object lock associated with a shared resource, before it can enter the shared resource. The runtime system ensures that no other thread can enter a shared resource if another thread already holds the object lock associated with the shared resource. If a thread cannot immediately acquire the object lock, it is blocked, that is, it must wait for the lock to become available.When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain access to the shared resource.
Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a
lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class
denotes this unique Class object. The class lock can be used in much the same way as an object lock to implement mutual exclusion.
There can be 2 ways through which synchronized can be implemented in Java:
  • synchronized methods
  • synchronized blocks
Synchronized statements are same as synchronized methods. A synchronized statement can only be
executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.

Synchronized Methods

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. .If the lock is already held by another thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when two or more threads simultaneously update the same value, and as a consequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.

Synchronized Blocks

Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A thread acquires the class lock before it can proceed with the execution of any static synchronized method in the class, blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
The general form of the synchronized block is as follows:
synchronized (<object reference expression>) {
<code block>
}
A compile-time error occurs if the expression produces a value of any primitive type. If execution of the block completes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released.
A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statements with identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, a NullPointerException is thrown.
The code block is usually related to the object on which the synchronization is being done. This is the case with synchronized methods, where the execution of the method is synchronized on the lock of the current object:
public Object method() {
synchronized (this) { // Synchronized block on current object
// method block
}
}
Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be able to execute the code block, or any other code requiring the same object lock, until the lock is relinquished. This happens when the execution of the code block completes normally or an uncaught exception is thrown.
Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of a part of a method, by using the this reference and putting the relevant part of the method in the synchronized block. The braces of the block cannot be left out, even if the code block has just one statement.

class SmartClient {
BankAccount account;
// …
public void updateTransaction() {
synchronized (account) { // (1) synchronized block
account.update(); // (2)
}
}
}

In summary, a thread can hold a lock on an object
  • by executing a synchronized instance method of the object
  • by executing the body of a synchronized block that synchronizes on the object
  • by executing a synchronized static method of a class
Thread States
A Java thread is always in one of several states which could be running, sleeping, dead, etc.
A thread can be in any of the following states:
  • New Thread state (Ready-to-run state)
  • Runnable state (Running state)
  • Not Runnable state
  • Dead state

New Thread

A thread is in this state when the instantiation of a Thread object creates a new thread but does not
start it running. A thread starts life in the Ready-to-run state. You can call only the start() or stop()
methods when the thread is in this state. Calling any method besides start() or stop() causes an
IllegalThreadStateException.

Runnable

When the start() method is invoked on a New Thread() it gets to the runnable state or running state by calling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.

Not Runnable

A thread becomes Not Runnable when one of the following four events occurs:
  • When sleep() method is invoked and it sleeps for a specified amount of time
  • When suspend() method is invoked
  • When the wait() method is invoked and the thread waits for notification of a free resource or waits for
    the completion of another thread or waits to acquire a lock of an object.
  • The thread is blocking on I/O and waits for its completion
Example: Thread.currentThread().sleep(1000);
Note: Thread.currentThread() may return an output like Thread[threadA,5,main]
The output shown in bold describes
  • the name of the thread,
  • the priority of the thread, and
  • the name of the group to which it belongs.
A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object or at the end of the period of time for sleep is over. Whether or not it will actually start running depends on its priority and the availability of the CPU.

How a thread switches form a non runnable to a runnable state:


  • If a thread has been put to sleep, then the specified number of milliseconds must elapse (or it must be interrupted).



  • If a thread has been suspended, then its resume() method must be invoked



  • If a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by calling
    either
     notify() or notifyAll().



  • If a thread is blocked on I/O, then the I/O must complete. 


  • Dead State
    A thread enters this state when the run() method has finished executing or when the stop() method is invoked. Once in this state, the thread cannot ever run again.

    Thread Priority

    In Java we can specify the priority of each thread relative to other threads. Those threads having higher priority get greater access to available resources then lower priority threads. A Java thread inherits its priority from the thread that created it. Heavy reliance on thread priorities for the behavior of a program can make the program non portable across platforms, as thread scheduling is host platform–dependent.You can modify a thread’s priority at any time after its creation using the setPriority() method and retrieve the thread priority value using getPriority() method.
    The following static final integer constants are defined in the
     Thread class:
    • MIN_PRIORITY (0) Lowest Priority
    • NORM_PRIORITY (5) Default Priority
    • MAX_PRIORITY (10) Highest Priority
    The priority of an individual thread can be set to any integer value between and including the above defined constants.When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.“If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true:
    • a higher priority thread becomes Runnable. (Pre-emptive scheduling)
    • it yields, or its run() method exits
    • on systems that support time-slicing, its time allotment has expired

    Thread Scheduler

    Schedulers in JVM implementations usually employ one of the two following strategies:
    Preemptive scheduling
    If a thread with a higher priority than all other Runnable threads becomes Runnable, the scheduler will preempt the running thread (is moved to the runnable state) and choose the new higher priority thread for execution.
    Time-Slicing or Round-Robin scheduling
    A running thread is allowed to execute for a fixed length of time (a time slot it’s assigned to), after which it moves to the Ready-to-run state (runnable) to await its turn to run again.
    A thread scheduler is implementation and platform-dependent; therefore, how threads will be scheduled is unpredictable across different platforms.

    Yielding

    A call to the static method yield(), defined in the Thread class, will cause the current thread in the Running state to move to the Runnable state, thus relinquishing the CPU. The thread is then at the mercy of the thread scheduler as to when it will run again. If there are no threads waiting in the Ready-to-run state, this thread continues execution. If there are other threads in the Ready-to-run state, their priorities determine which thread gets to execute. The yield() method gives other threads of the same priority a chance to run. If there are no equal priority threads in the “Runnable” state, then the yield is ignored.

    Sleeping and Waking Up

    The thread class contains a static method named sleep() that causes the currently running thread to pause its execution and transit to the Sleeping state. The method does not relinquish any lock that the thread might have. The thread will sleep for at least the time specified in its argument, before entering the runnable state where it takes its turn to run again. If a thread is interrupted while sleeping, it will throw an InterruptedException when it awakes and gets to execute. The Thread class has several overloaded versions of the sleep() method.

    Waiting and Notifying

    Waiting and notifying provide means of thread inter-communication that synchronizes on the same object. The threads execute wait() and notify() (or notifyAll()) methods on the shared object for this purpose. The notifyAll(), notify() and wait() are methods of the Object class. These methods can be invoked only from within a synchronized context (synchronized method or synchronized block), otherwise, the call will result in an IllegalMonitorStateException. The notifyAll() method wakes up all the threads waiting on the resource. In this situation, the awakened threads compete for the resource. One thread gets the resource and the others go back to waiting.
    wait() method signatures
    final void wait(long timeout) throws InterruptedException
    final void wait(long timeout, int nanos) throws InterruptedException
    final void wait() throws InterruptedException .     
    wait() call can specify the time the thread should wait before being timed out. An another thread can invoke an interrupt() method on a waiting thread resulting in an InterruptedException. This is a checked exception and hence the code with the wait() method must be enclosed within a try catch block.  
    notify() method signatures
    final void notify()
    final void notifyAll()
    A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met. The thread leaves the Running state and transits to the Waiting-for-notification state. There it waits for this condition to occur. The thread relinquishes ownership of the object lock. The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object after acquiring its lock.
    The wait() method causes the current thread to wait until another thread notifies it of a condition change.
    Joining A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
    Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to the Blocked-for-join-completion state.

    Deadlock

    There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.
    Note: 
    The following methods namely join, sleep and wait name the InterruptedException in its throws clause and can have a timeout argument as a parameter. The following methods namely wait, notify and notifyAllshould only be called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start method causes a new thread to get ready to run at the discretion of the thread scheduler. The Runnable interface declares the run method. The Thread class implements the Runnable interface. Some implementations of the Thread.yield method will not yield to a thread of lower priority. A program will terminate only when all user threads stop running. A thread inherits its daemon status from the thread that created it

    No comments:

    Post a Comment