Search Java Programs

Monday, March 8, 2010

Introduction to Threads

Introduction to Threads

Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.

Multithreading has several advantages over Multiprocessing such as;

  • Threads are lightweight compared to processes
  • 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.

The following figure shows the methods that are members of the Object and Thread Class.

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)

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.

class RunnableThread implements Runnable {

Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}

public class RunnableExample {

public static void main(String[] args) {
Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

Output

thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private

Download Runnable Thread Program Example

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.

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.


class XThread extends Thread {

XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample {

public static void main(String[] args) {
Thread thread1 = new Thread(new XThread(), "thread1");
Thread thread2 = new Thread(new XThread(), "thread2");
// The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread("thread5");
//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}


Output

Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]

Download Java Thread Program Example

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.

An example of an anonymous class below shows how to create a thread and start it:

( new Thread() {

public void run() {

for(;;) System.out.println(”Stop the world!”);

}

}

).start();


Thread 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 otherwise lead to dirty reads and significant errors.
Generally critical sections of the code are usually marked with synchronized keyword.

Examples 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.

Below is an example shows how synchronized methods and object locks are used to coordinate access to a common object by multiple threads. If the ’synchronized’ keyword is removed, the message is displayed in random fashion.



public class SyncMethodsExample extends Thread {

static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com",
"is", "the", "best" };
public SyncMethodsExample(String id) {
super(id);
}
public static void main(String[] args) {
SyncMethodsExample thread1 = new SyncMethodsExample("thread1: ");
SyncMethodsExample thread2 = new SyncMethodsExample("thread2: ");
thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do {
if (t1IsAlive && !thread1.isAlive()) {
t1IsAlive = false;
System.out.println("t1 is dead.");
}
if (t2IsAlive && !thread2.isAlive()) {
t2IsAlive = false;
System.out.println("t2 is dead.");
}
} while (t1IsAlive || t2IsAlive);
}
void randomWait() {
try {
Thread.currentThread().sleep((long) (3000 * Math.random()));
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
}
public synchronized void run() {
SynchronizedOutput.displayList(getName(), msg);
}
}

class SynchronizedOutput {

// if the 'synchronized' keyword is removed, the message
// is displayed in random fashion
public static synchronized void displayList(String name, String list[]) {
for (int i = 0; i <>
SyncMethodsExample t = (SyncMethodsExample) Thread
.currentThread();
t.randomWait();
System.out.println(name + list[i]);
}
}
}

Output

thread1: Beginner
thread1: java
thread1: tutorial,
thread1: .,
thread1: com
thread1: is
thread1: the
thread1: best
t1 is dead.
thread2: Beginner
thread2: java
thread2: tutorial,
thread2: .,
thread2: com
thread2: is
thread2: the
thread2: best
t2 is dead.

Download Synchronized Methods Thread Program Example

Class Locks

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 the previous example, the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object. If several threads were to concurrently execute the method updateTransaction() on an object of SmartClient, the statement at (2) would be executed by one thread at a time, only after synchronizing on the BankAccount object associated with this particular instance of SmartClient.

Inner classes can access data in their enclosing context. An inner object might need to synchronize on its associated outer object, in order to ensure integrity of data in the latter. This is illustrated in the following code where the synchronized block at (5) uses the special form of the this reference to synchronize on the outer object associated with an object of the inner class. This setup ensures that a thread executing the method setPi() in an inner object can only access the private double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associated outer object. If another thread has the lock of the associated outer object, the thread in the inner object has to wait for the lock to be relinquished before it can proceed with the execution of the synchronized block at (5). However, synchronizing on an inner object and on its associated outer object are independent of each other, unless enforced explicitly, as in the following code:

class Outer { // (1) Top-level Class
private double myPi; // (2)
protected class Inner { // (3) Non-static member Class
public void setPi() { // (4)
synchronized(Outer.this) { // (5) Synchronized block on outer object
myPi = Math.PI; // (6)
}
}
}
}

Below example shows how synchronized block and object locks are used to coordinate access to shared objects by multiple threads.


public class SyncBlockExample extends Thread {

static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com",
"is", "the", "best" };
public SyncBlockExample(String id) {
super(id);
}
public static void main(String[] args) {
SyncBlockExample thread1 = new SyncBlockExample("thread1: ");
SyncBlockExample thread2 = new SyncBlockExample("thread2: ");
thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do {
if (t1IsAlive && !thread1.isAlive()) {
t1IsAlive = false;
System.out.println("t1 is dead.");
}
if (t2IsAlive && !thread2.isAlive()) {
t2IsAlive = false;
System.out.println("t2 is dead.");
}
} while (t1IsAlive || t2IsAlive);
}
void randomWait() {
try {
Thread.currentThread().sleep((long) (3000 * Math.random()));
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
}
public void run() {
synchronized (System.out) {
for (int i = 0; i < msg.length; i++) { randomWait(); System.out.println(getName() + msg[i]); } } } }

Output

thread1: Beginner
thread1: java
thread1: tutorial,
thread1: .,
thread1: com
thread1: is
thread1: the
thread1: best
t1 is dead.
thread2: Beginner
thread2: java
thread2: tutorial,
thread2: .,
thread2: com
thread2: is
thread2: the
thread2: best
t2 is dead.

Synchronized blocks can also be specified on a class lock:

synchronized (.class) { }

The block synchronizes on the lock of the object denoted by the reference .class. A static synchronized method
classAction() in class A is equivalent to the following declaration:

static void classAction() {

synchronized (A.class) { // Synchronized block on class A

// …

}

}

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.

Here, the run() method put itself to sleep for one second and becomes Not Runnable during that period.
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.

Hence I hereby list the scenarios below to describe 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

The 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.

A thread in the Waiting-for-notification state can be awakened by the occurrence of any one of these three incidents:

1. Another thread invokes the notify() method on the object of the waiting thread, and the waiting thread is selected as the thread to be awakened.
2. The waiting thread times out.
3. Another thread interrupts the waiting thread.

Notify

Invoking the notify() method on an object wakes up a single thread that is waiting on the lock of this object.
A call to the notify() method has no consequences if there are no threads in the wait set of the object.
The notifyAll() method wakes up all threads in the wait set of the shared object.

Below program shows three threads, manipulating the same stack. Two of them are pushing elements on the stack, while the third one is popping elements off the stack. This example illustrates how a thread waiting as a result of calling the wait() method on an object, is notified by another thread calling the notify() method on the same object


class StackClass {

private Object[] stackArray;
private volatile int topOfStack;
StackClass(int capacity) {
stackArray = new Object[capacity];
topOfStack = -1;
}
public synchronized Object pop() {
System.out.println(Thread.currentThread() + ": popping");
while (isEmpty()) {
try {
System.out.println(Thread.currentThread()
+ ": waiting to pop");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object obj = stackArray[topOfStack];
stackArray[topOfStack--] = null;
System.out.println(Thread.currentThread()
+ ": notifying after pop");
notify();
return obj;
}
public synchronized void push(Object element) {
System.out.println(Thread.currentThread() + ": pushing");
while (isFull()) {
try {
System.out.println(Thread.currentThread()
+ ": waiting to push");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stackArray[++topOfStack] = element;
System.out.println(Thread.currentThread()
+ ": notifying after push");
notify();
}
public boolean isFull() {
return topOfStack >= stackArray.length - 1;
}
public boolean isEmpty() {
return topOfStack < 0; } } abstract class StackUser extends Thread { protected StackClass stack; StackUser(String threadName, StackClass stack) { super(threadName); this.stack = stack; System.out.println(this); setDaemon(true); start(); } } class StackPopper extends StackUser { // Stack Popper StackPopper(String threadName, StackClass stack) { super(threadName, stack); } public void run() { while (true) { stack.pop(); } } } class StackPusher extends StackUser { // Stack Pusher StackPusher(String threadName, StackClass stack) { super(threadName, stack); } public void run() { while (true) { stack.push(new Integer(1)); } } } public class WaitAndNotifyExample { public static void main(String[] args) { StackClass stack = new StackClass(5); new StackPusher("One", stack); new StackPusher("Two", stack); new StackPopper("Three", stack); System.out.println("Main Thread sleeping."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Exit from Main Thread."); } }

Download Wait Notify methods Thread Program Example

The field topOfStack in class StackClass is declared volatile, so that read and write operations on this variable will access the master value of this variable, and not any copies, during runtime.
Since the threads manipulate the same stack object and the push() and pop() methods in the class StackClassare synchronized, it means that the threads synchronize on the same object.

How the program uses wait() and notify() for inter thread communication.

(1) The synchronized pop() method - When a thread executing this method on the StackClass object finds that the stack is empty, it invokes the wait() method in order to wait for some other thread to fill the stack by using the synchronized push. Once an other thread makes a push, it invokes the notify method.
(2)The synchronized push() method - When a thread executing this method on the StackClass object finds that the stack is full, i t invokes the wait() method to await some other thread to remove an element to provide space for the newly to be pushed element.
Once an other thread makes a pop, it invokes the notify method.

–~~~~~~~~~~~~–

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.

Below is a program showing how threads invoke the overloaded thread join method.

public class ThreadJoinDemo {

public static void main(String[] args) {
Thread t1 = new Thread("T1");
Thread t2 = new Thread("T2");
try {
System.out.println("Wait for the child threads to finish.");
t1.join();
if (!t1.isAlive())
System.out.println("Thread T1 is not alive.");
t2.join();
if (!t2.isAlive())
System.out.println("Thread T2 is not alive.");
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted.");
}
System.out.println("Exit from Main Thread.");
}
}

Download Java Thread Join Method Program Example

Output

Wait for the child threads to finish.
Thread T1 is not alive.
Thread T2 is not alive.
Exit from Main Thread.

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.

Thread t1 at tries to synchronize first on string o1 and then on string o2. The thread t2 does the opposite. It synchronizes first on string o2 then on string o1. Hence a deadlock can occur as explained above.

Below is a program that illustrates deadlocks in multithreading applications


public class DeadLockExample {

String o1 = "Lock ";
String o2 = "Step ";
Thread t1 = (new Thread("Printer1") {

public void run() {
while (true) {
synchronized (o1) {
synchronized (o2) {
System.out.println(o1 + o2);
}
}
}
}
});
Thread t2 = (new Thread("Printer2") {

public void run() {
while (true) {
synchronized (o2) {
synchronized (o1) {
System.out.println(o2 + o1);
}
}
}
}
});
public static void main(String[] args) {
DeadLockExample dLock = new DeadLockExample();
dLock.t1.start();
dLock.t2.start();
}
}

Download Java Thread deadlock Program Example

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 notifyAll should 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

Thursday, March 4, 2010

Advance Methods Program in Java

Java Theory Class

Java Programming Video Tutorials

Java Practical Program

SCJP Paper Notes

SCJP Notes Chapter 1

Chapter 1: Language Fundamentals

The Java programming language has includes five simple arithmetic operators like are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). The following table summarizes them:

. Source file's elements (in order)
  • Package declaration
  • Import statements
  • Class definitions

2. Importing packages doesn't recursively import sub-packages.

3. Sub-packages are really different packages, happen to live within an enclosing package. Classes in sub-packages cannot access classes in enclosing package with default access.

4. Comments can appear anywhere. Can't be nested. No matter what type of comments.

5. At most one public class definition per file. This class name should match the file name. If there are more than one public class definitions, compiler will accept the class with the file's name and give an error at the line where the other class is defined.

6. It's not required having a public class definition in a file. Strange, but true. J In this case, the file's name should be different from the names of classes and interfaces (not public obviously).

7. Even an empty file is a valid source file.

8. An identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.

9. An identifier cannot have a name of a Java keyword. Embedded keywords are OK. true, false and null are literals (not keywords), but they can't be used as identifiers as well.

10. const and goto are reserved words, but not used.

11. Unicode characters can appear anywhere in the source code. The following code is valid.

ch\u0061r a = 'a';

char \u0062 = 'b';

char c = '\u0063';

12. Java has 8 primitive data types.

Data Type

Size (bits)

Initial Value

Min Value

Max Value

boolean

1

false

false

true

byte

8

0

-128 (-27)

127 (27 - 1)

short

16

0

-215

215 - 1

char

16

'\u0000'

'\u0000' (0)

'\uFFFF' (216 - 1)

int

32

0

-231

231 - 1

long

64

0L

-263

263 - 1

float

32

0.0F

1.4E-45

3.4028235E38

double

64

0.0

4.9E-324

1.7976931348623157E308


13. All numeric data types are signed. char is the only unsigned integral type.

14. Object reference variables are initialized to null.

15. Octal literals begin with zero. Hex literals begin with 0X or 0x.

16. Char literals are single quoted characters or unicode values (begin with \u).

17. A number is by default an int literal, a decimal number is by default a double literal.

18. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that it's an identifier)

19. Two types of variables.

a. Member variables

  • Accessible anywhere in the class.
  • Automatically initialized before invoking any constructor.
  • Static variables are initialized at class load time.
  • Can have the same name as the class.
b. Automatic variables method local

· Must be initialized explicitly. (Or, compiler will catch it.) Object references can be initialized to null to make the compiler happy. The following code won't compile. Specify else part or initialize the local variable explicitly.

public String testMethod ( int a) {

String tmp;

if ( a > 0 ) tmp = "Positive";

return tmp;

}

· Can have the same name as a member variable, resolution is based on scope.

20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created.

21. Arrays should be
  • Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
  • Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
  • Initialized. for (int i = 0; i <>

22. The above three can be done in one step.

int a[] = { 1, 2, 3 }; (or )

int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.

23. Java arrays are static arrays. Size has to be specified at compile time. Array.length returns array's size. (Use Vectors for dynamic purposes).

24. Array size is never specified with the reference variable, it is always maintained with the array object. It is maintained in array.length, which is a final instance variable.

25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]

26. Arrays with zero elements can be created. args array to the main method will be a zero element array if no command parameters are specified. In this case args.length is 0.

27. Comma after the last initializer in array declaration is ignored.

int[] i = new int[2] { 5, 10}; // Wrong

int i[5] = { 1, 2, 3, 4, 5}; // Wrong

int[] i[] = {{}, new int[] {} }; // Correct

int i[][] = { {1,2}, new int[2] }; // Correct

int i[] = { 1, 2, 3, 4, } ; // Correct

28. Array indexes start with 0. Index is an int data type.

29. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them.

30. Arrays declared even as member variables also need to be allocated memory explicitly.

static int a[];

static int b[] = {1,2,3};

public static void main(String s[]) {

System.out.println(a[0]); // Throws a null pointer exception

System.out.println(b[0]); // This code runs fine

System.out.println(a); // Prints 'null'

System.out.println(b); // Prints a string which is returned by toString

}

31. Once declared and allocated (even for local arrays inside methods), array elements are automatically initialized to the default values.

32. If only declared (not constructed), member array variables default to null, but local array variables will not default to null.

33. Java doesn't support multidimensional arrays formally, but it supports arrays of arrays. From the specification - "The number of bracket pairs indicates the depth of array nesting." So this can perform as a multidimensional array. (no limit to levels of array nesting)

34. In order to be run by JVM, a class should have a main method with the following signature.

public static void main(String args[])

static public void main(String[] s)

35. args array's name is not important. args[0] is the first argument. args.length gives no. of arguments.

36. main method can be overloaded.

37. main method can be final.

38. A class with a different main signature or w/o main method will compile. But throws a runtime error.

39. A class without a main method can be run by JVM, if its ancestor class has a main method. (main is just a method and is inherited)

40. Primitives are passed by value.

41. Objects (references) are passed by reference. The object reference itself is passed by value. So, it can't be changed. But, the object can be changed via the reference.

42. Garbage collection is a mechanism for reclaiming memory from objects that are no longer in use, and making the memory available for new objects.

43. An object being no longer in use means that it can't be referenced by any 'active' part of the program.

44. Garbage collection runs in a low priority thread. It may kick in when memory is too low. No guarantee.

45. It's not possible to force garbage collection. Invoking System.gc may start garbage collection process.

46. The automatic garbage collection scheme guarantees that a reference to an object is always valid while the object is in use, i.e. the object will not be deleted leaving the reference "dangling".

47. There are no guarantees that the objects no longer in use will be garbage collected and their finalizers executed at all. gc might not even be run if the program execution does not warrant it. Thus any memory allocated during program execution might remain allocated after program termination, unless reclaimed by the OS or by other means.

48. There are also no guarantees on the order in which the objects will be garbage collected or on the order in which the finalizers are called. Therefore, the program should not make any decisions based on these assumptions.

49. An object is only eligible for garbage collection, if the only references to the object are from other objects that are also eligible for garbage collection. That is, an object can become eligible for garbage collection even if there are references pointing to the object, as long as the objects with the references are also eligible for garbage collection.

50. Circular references do not prevent objects from being garbage collected.

51. We can set the reference variables to null, hinting the gc to garbage collect the objects referred by the variables. Even if we do that, the object may not be gc-ed if it's attached to a listener. (Typical in case of AWT components) Remember to remove the listener first.

52. All objects have a finalize method. It is inherited from the Object class.

53. finalize method is used to release system resources other than memory. (such as file handles and network connections) The order in which finalize methods are called may not reflect the order in which objects are created. Don't rely on it. This is the signature of the finalize method.

protected void finalize() throws Throwable { }

In the descendents this method can be protected or public. Descendents can restrict the exception list that can be thrown by this method.

54. finalize is called only once for an object. If any exception is thrown in finalize, the object is still eligible for garbage collection (at the discretion of gc)

55. gc keeps track of unreachable objects and garbage-collects them, but an unreachable object can become reachable again by letting know other objects of its existence from its finalize method (when called by gc). This 'resurrection' can be done only once, since finalize is called only one for an object.

56. finalize can be called explicitly, but it does not garbage collect the object.

57. finalize can be overloaded, but only the method with original finalize signature will be called by gc.

58. finalize is not implicitly chained. A finalize method in sub-class should call finalize in super class explicitly as its last action for proper functioning. But compiler doesn't enforce this check.

59. System.runFinalization can be used to run the finalizers (which have not been executed before) for the objects eligible for garbage collection.

SCJP Notes Chapter 2

Chapter 2 Operators and assignments

The Java programming language has included five simple arithmetic operators like + (addition), - (subtraction), * (multiplication), / (division)

1. Unary operators

1.1 Increment and Decrement operators ++ --

We have postfix and prefix notation. In post-fix notation value of the variable/expression is modified after the value is taken for the execution of statement. In prefix notation, value of the variable/expression is modified before the value is taken for the execution of statement.

x = 5; y = 0; y = x++; Result will be x = 6, y = 5

x = 5; y = 0; y = ++x; Result will be x = 6, y = 6

Implicit narrowing conversion is done, when applied to byte, short or char.

1.2 Unary minus and unary plus + -

+ has no effect than to stress positivity.

- negates an expression's value. (2's complement for integral expressions)

1.3 Negation !

Inverts the value of a boolean expression.

1.4 Complement ~

Inverts the bit pattern of an integral expression. (1's complement - 0s to 1s and 1s to 0s)

Cannot be applied to non-integral types.

1.5 Cast ()

Persuades compiler to allow certain assignments. Extensive checking is done at compile and runtime to ensure type-safety.

2. Arithmetic operators - *, /, %, +, -

· Can be applied to all numeric types.

· Can be applied to only the numeric types, except '+' - it can be applied to Strings as well.

· All arithmetic operations are done at least with 'int'. (If types are smaller, promotion happens. Result will be of a type at least as wide as the wide type of operands)

· Accuracy is lost silently when arithmetic overflow/error occurs. Result is a nonsense value.

· Integer division by zero throws an exception.

· % - reduce the magnitude of LHS by the magnitude of RHS. (continuous subtraction)

· % - sign of the result entirely determined by sign of LHS

· 5 % 0 throws an ArithmeticException.

· Floating point calculations can produce NaN (square root of a negative no) or Infinity ( division by zero). Float and Double wrapper classes have named constants for NaN and infinities.

· NaN's are non-ordinal for comparisons. x == Float.NaN won't work. Use Float.IsNaN(x) But equals method on wrapper objects(Double or Float) with NaN values compares Nan's correctly.

· Infinities are ordinal. X == Double.POSITIVE_INFINITY will give expected result.

· + also performs String concatenation (when any operand in an expression is a String). The language itself overloads this operator. toString method of non-String object operands are called to perform concatenation. In case of primitives, a wrapper object is created with the primitive value and toString method of that object is called. ("Vel" + 3 will work.)

· Be aware of associativity when multiple operands are involved.

System.out.println( 1 + 2 + "3" ); // Prints 33

System.out.println( "1" + 2 + 3 ); // Prints 123

3. Shift operators - <<, >>, >>>

· <<>> performs a signed right shift. Sign bit is brought in from the left. (0 if positive, 1 if negative. Value becomes old value / 2 ^ x where x is no of bits shifted. Also called arithmetic right shift.

· >>> performs an unsigned logical right shift. 0 bits are brought in from the left. This operator exists since Java doesn't provide an unsigned data type (except char). >>> changes the sign of a negative number to be positive. So don't use it with negative numbers, if you want to preserve the sign. Also don't use it with types smaller than int. (Since types smaller than int are promoted to an int before any shift operation and the result is cast down again, so the end result is unpredictable.)

· Shift operators can be applied to only integral types.

· -1 >> 1 is -1, not 0. This differs from simple division by 2. We can think of it as shift operation rounding down.

· 1 << x =" x">> 33; // Here actually what happens is x >> 1

4. Comparison operators - all return boolean type.

4.1 Ordinal comparisons - <, <=, > , >=

· Only operate on numeric types. Test the relative value of the numeric operands.

· Arithmetic promotions apply. char can be compared to float.

4.2 Object type comparison - instanceof

· Tests the class of an object at runtime. Checking is done at compile and runtime same as the cast operator.

· Returns true if the object denoted by LHS reference can be cast to RHS type.

· LHS should be an object reference expression, variable or an array reference.

· RHS should be a class (abstract classes are fine), an interface or an array type, castable to LHS object reference. Compiler error if LHS & RHS are unrelated.

· Can't use java.lang.Class or its String name as RHS.

· Returns true if LHS is a class or subclass of RHS class

· Returns true if LHS implements RHS interface.

· Returns true if LHS is an array reference and of type RHS.

· x instanceof Component[] - legal.

· x instanceof [] - illegal. Can't test for 'any array of any type'

· Returns false if LHS is null, no exceptions are thrown.

· If x instanceof Y is not allowed by compiler, then Y y = (Y) x is not a valid cast expression. If x instanceof Y is allowed and returns false, the above cast is valid but throws a ClassCastException at runtime. If x instanceof Y returns true, the above cast is valid and runs fine.

4.3 Equality comparisons - ==, !=

· For primitives it's a straightforward value comparison. (promotions apply)

· For object references, this doesn't make much sense. Use equals method for meaningful comparisons. (Make sure that the class implements equals in a meaningful way, like for X.equals(Y) to be true, Y instance of X must be true as well)

· For String literals, == will return true, this is because of compiler optimization.

5. Bit-wise operators - &, ^, |

· Operate on numeric and boolean operands.

· & - AND operator, both bits must be 1 to produce 1.

· | - OR operator, any one bit can be 1 to produce 1.

· ^ - XOR operator, any one bit can be 1, but not both, to produce 1.

· In case of booleans true is 1, false is 0.

· Can't cast any other type to boolean.

6. Short-circuit logical operators - &&, ||

· Operate only on boolean types.

· RHS might not be evaluated (hence the name short-circuit), if the result can be determined only by looking at LHS.

· false && X is always false.

· true || X is always true.

· RHS is evaluated only if the result is not certain from the LHS.

· That's why there's no logical XOR operator. Both bits need to be known to calculate the result.

· Short-circuiting doesn't change the result of the operation. But side effects might be changed. (i.e. some statements in RHS might not be executed, if short-circuit happens. Be careful)

7. Ternary operator

· Format a = x ? b : c ;

· x should be a boolean expression.

· Based on x, either b or c is evaluated. Both are never evaluated.

· b will be assigned to a if x is true, else c is assigned to a.

· b and c should be assignment compatible to a.

· b and c are made identical during the operation according to promotions.

8. Assignment operators.

· Simple assignment =.

· op= calculate and assign operators extended assignment operators.

· *=, /=, %=, +=, -=

· x += y means x = x + y. But x is evaluated only once. Be aware.

· Assignment of reference variables copies the reference value, not the object body.

· Assignment has value, value of LHS after assignment. So a = b = c = 0 is legal. c = 0 is executed first, and the value of the assignment (0) assigned to b, then the value of that assignment (again 0) is assigned to a.

· Extended assignment operators do an implicit cast. (Useful when applied to byte, short or char)

byte b = 10;

b = b + 10; // Won't compile, explicit cast required since the expression evaluates to an int

b += 10; // OK, += does an implicit cast from int to byte

9. General

· In Java, No overflow or underflow of integers happens. i.e. The values wrap around. Adding 1 to the maximum int value results in the minimum value.

· Always keep in mind that operands are evaluated from left to right, and the operations are executed in the order of precedence and associativity.

· Unary Postfix operators and all binary operators (except assignment operators) have left to right assoiciativity.

· All unary operators (except postfix operators), assignment operators, ternary operator, object creation and cast operators have right to left assoiciativity.

· Inspect the following code.

public class Precedence {

final public static void main(String args[]) {

int i = 0;

i = i++;

i = i++;

i = i++;

System.out.println(i); // prints 0, since = operator has the lowest precedence.

int array[] = new int[5];

int index = 0;

array[index] = index = 3; // 1st element gets assigned to 3, not the 4th element

for (int c = 0; c < style="">

Type of Operators

Operators

Associativity

Postfix operators

[] . (parameters) ++ --

Left to Right

Prefix Unary operators

++ -- + - ~ !

Right to Left

Object creation and cast

new (type)

Right to Left

Multiplication/Division/Modulus

* / %

Left to Right

Addition/Subtraction

+ -

Left to Right

Shift

>> >>> <<

Left to Right

Relational

< <= > >= instanceof

Left to Right

Equality

== !=

Left to Right

Bit-wise/Boolean AND

&

Left to Right

Bit-wise/Boolean XOR

^

Left to Right

Bit-wise/Boolean OR

|

Left to Right

Logical AND (Short-circuit or Conditional)

&&

Left to Right

Logical OR (Short-circuit or Conditional)

||

Left to Right

Ternary

? :

Right to Left

Assignment

= += -= *= /= %= <<= >>= >>>= &= ^= |=

Right to Left


Website Design by Mayuri Multimedia