You are on page 1of 124

UNIT - 4

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exception Handling

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Syntax Errors, Runtime Errors, and Logic
Errors
You learned that there are three categories of
errors: syntax errors, runtime errors, and logic
errors. Syntax errors arise because the rules of
the language have not been followed. They are
detected by the compiler. Runtime errors occur
while the program is running if the environment
detects an operation that is impossible to carry
out. Logic errors occur when a program doesn't
perform the way it was intended to.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Runtime Errors
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.

Run

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catch Runtime Errors
1 import java.util.*; Run
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 } while (continueInput);
25 }
13 }
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exception Classes
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
System Errors
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

System errors are thrown by JVM Several more classes


LinkageError
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely VirtualMachineError

occur. If one does, there is little Error


you can do beyond notifying the AWTError
user and trying to terminate the
program gracefully. Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exceptions
Exception describes errors ClassNotFoundException
caused by your program
and external IOException
circumstances. These ArithmeticException
errors can be caught and Exception AWTException
handled by your program. NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Runtime Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError RuntimeException is caused by


Error programming errors, such as bad
casting, accessing an out-of-bounds
AWTError
array, and numeric errors.

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked Exceptions vs. Unchecked
Exceptions

RuntimeException, Error and their subclasses are


known as unchecked exceptions. All other
exceptions are known as checked exceptions,
meaning that the compiler forces the programmer
to check and deal with the exceptions.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Unchecked Exceptions
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to
it; an IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array.
These are the logic errors that should be corrected in the
program. Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-catch
blocks, Java does not mandate you to write code to catch
unchecked exceptions.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked or Unchecked Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error Unchecked
exception.
AWTError

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring, Throwing, and Catching
Exceptions

method1() { declare exception


method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as
declaring exceptions.

public void myMethod()


throws IOException

public void myMethod()


throws IOException, OtherException

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate
exception type and throw it. This is known as
throwing an exception. Here is an example,

throw new TheException();

TheException ex = new TheException();


throw ex;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catching Exceptions

main method { method1 { method2 { An exception


... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).

void p1() { void p1() throws IOException {


try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}

(a) (b)

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution

The final block is


try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution

Next statement in the


try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation

Trace a Program Execution


try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Cautions When Using Exceptions
• Exception handling separates error-handling
code from normal programming tasks, thus
making programs easier to read and to modify.
Be aware, however, that exception handling
usually requires more time and resources
because it requires instantiating a new
exception object, rolling back the call stack, and
propagating the errors to the calling methods.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
When to Throw Exceptions
• An exception occurs in a method. If you want
the exception to be processed by its caller, you
should create an exception object and throw it.
If you can handle the exception in the method
where it occurs, there is no need to throw it.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
When to Use Exceptions
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Creating Custom Exception Classes
 Use the exception classes in the API whenever possible.
 Create custom exception classes if the predefined
classes are not sufficient.
 Declare custom exception classes by extending
Exception or a subclass of Exception.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Custom Exception Class Example
In Listing 17.1, the setRadius method throws an exception if the
radius is negative. Suppose you wish to pass the radius to the
handler, you have to create a custom exception class.

InvalidRadiusException

CircleWithRadiusException

TestCircleWithRadiusException Run

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Creating Own Exception Classes

• Built-in exception classes handle some generic


errors.
• For application-specific errors define your own
exception classes. How? Define a subclass of
Exception:
class MyException extends Exception { … }
• MyException need not implement anything – its
mere existence in the type system allows to use its
objects as exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: Own Exceptions 1

• A new exception class is defined, with a private detail


variable, a one parameter constructor and an overridden
toString method:
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: Own Exceptions 2

class ExceptionDemo {
The static compute method throws the MyException
exception whenever its a argument is greater than 10:
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if (a > 10) throw new MyException(a);
System.out.println("Normal exit");
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: Own Exceptions 3

The main method calls compute with two arguments


within a try block that catches the MyException exception:
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Multi threading

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Differences between multi threading and
multitasking

Multi-Tasking
• Two kinds of multi-tasking:
1) process-based multi-tasking
2) thread-based multi-tasking
• Process-based multi-tasking is about allowing several programs to execute
concurrently, e.g. Java compiler and a text editor.
• Processes are heavyweight tasks:
1) that require their own address space
2) inter-process communication is expensive and limited
3) context-switching from one process to another is expensive
and limited

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread-Based Multi-Tasking

• Thread-based multi-tasking is about a single program


executing concurrently
• several tasks e.g. a text editor printing and spell-checking
text.
• Threads are lightweight tasks:
1) they share the same address space
2) they cooperatively share the same process
3) inter-thread communication is inexpensive
4) context-switching from one thread to another
is low-cost
• Java multi-tasking is thread-based.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Reasons for Multi-Threading

• Multi-threading enables to write efficient programs that


make the maximum use of the CPU, keeping the idle time to
a minimum.
• There is plenty of idle time for interactive, networked
applications:
1) the transmission rate of data over a network is much
slower than the rate at which the computer can process it
2) local file system resources can be read and written at a
much slower rate than can be processed by the CPU
3) of course, user input is much slower than the computer

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Diff between Thread vs Process

Thread
Process
1. Light Weight Process 1.Heavy weight Process
2. Do not require separate address
space for its execution.Runs in the 2. Requires separate address
address space of the process to space
which it belongs to

3. Thread based multitasking – 3. Process based multitasking –


Multithreading Multiprocessing.

4. Cost of communication between


the thread is low 4. Cost of communication
between the process is high
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Lifecycle

• Thread exist in several states:


1) ready to run
2) running
3) a running thread can be suspended
4) a suspended thread can be resumed
5) a thread can be blocked when waiting for a resource
6) a thread can be terminated
• Once terminated, a thread cannot be resumed.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
IsAlive & Join
• final boolean isAlive( )
– The isAlive( ) method returns true if the thread upon
which it is called is still running. It returns false
otherwise.
• final void join( ) throws InterruptedException
– This method waits until the thread on which it is
called terminates
– we tell our thread to wait until the specified thread
completes its execution.
– It means - "join" start of a thread's execution to end of
another thread's execution
– – thus thread will not start until other thread is done.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Creating Thread
• Two ways to create a thread:
– By extending Thread class
– By implementing Runnable interface.
• Implementatio
n of thread

Extending Implementing
Thread – Runnable
Class Interface
Overrides
Run()
method
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Extending thread class - example
• class Multi extends Thread{
• public void run(){
• System.out.println("thread is running...");
• }
• public static void main(String args[]){
• Multi t1=new Multi();
• t1.start();
• }
• }

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Using Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Creating Threads

• To create a new thread a program will:


1) extend the Thread class, or
2) implement the Runnable interface
• Thread class encapsulates a thread of
execution.
• The whole Java multithreading environment is
based on the Thread class.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Methods

• Start: a thread by calling start its run method


• Sleep: suspend a thread for a period of time
• Run: entry-point for a thread
• Join: wait for a thread to terminate
• isAlive: determine if a thread is still running
• getPriority: obtain a thread’s priority
• getName: obtain a thread’s name
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
New Thread: Runnable

• To create a new thread by implementing the Runnable


interface:
1) create a class that implements the run method (inside this
method, we define the code that constitutes the new
thread):
public void run()
2) instantiate a Thread object within that class, a possible
constructor is:
Thread(Runnable threadOb, String threadName)
3) call the start method on this object (start calls run):
void start()

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 1

• A class NewThread that implements Runnable:


class NewThread implements Runnable {
Thread t;
//Creating and starting a new thread. Passing this to the
// Thread constructor – the new thread will call this
// object’s run method:
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 2

//This is the entry point for the newly created thread – a five-iterations loop
//with a half-second pause between the iterations all within try/catch:
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 3

class ThreadDemo {
public static void main(String args[]) {
//A new thread is created as an object of
// NewThread:
new NewThread();
//After calling the NewThread start method,
// control returns here.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 4

//Both threads (new and main) continue concurrently.


//Here is the loop for the main thread:
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
New Thread: Extend Thread

• The second way to create a new thread:


1) create a new class that extends Thread
2) create an instance of that class
• Thread provides both run and start methods:
1) the extending class must override run
2) it must also call the start method

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 1

• The new thread class extends Thread:


class NewThread extends Thread {
//Create a new thread by calling the Thread’s
// constructor and start method:
NewThread() {
super("Demo Thread");
System.out.println("Child thread: " + this);
start();
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 2

NewThread overrides the Thread’s run method:


public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 3

class ExtendThread {
public static void main(String args[]) {
//After a new thread is created:
new NewThread();
//the new and main threads continue
//concurrently…

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 4

//This is the loop of the main thread:


try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Threads: Synchronization

• Multi-threading introduces asynchronous behavior to a program.


• How to ensure synchronous behavior when we need it?
• For instance, how to prevent two threads from simultaneously
writing and reading the same object?
• Java implementation of monitors:
1) classes can define so-called synchronized methods
2) each object has its own implicit monitor that is automatically
entered when one of the object’s synchronized methods is called
3) once a thread is inside a synchronized method, no other thread
can call any other synchronized method on the same object

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Synchronization

• Language keyword: synchronized


• Takes out a monitor lock on an object
– Exclusive lock for that thread
• If lock is currently unavailable, thread will block

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Synchronization

• Protects access to code, not to data


– Make data members private
– Synchronize accessor methods
• Puts a “force field” around the locked object
so no other threads can enter
• Actually, it only blocks access to other synchronizing
threads

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
// This program is not synchronized.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Output:
[Hello[Synchronized[World]
]
]

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Race Condition
• Nothing exists to stop all three threads from
calling the same method, on the same object,
at the same time. This is known as a race
condition, because the three threads are racing
each other to complete the method.
class Callme {
synchronized void call(String msg) {
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Synchronized Statement
• Conceptually threads in Java execute concurrently and therefore
could simultaneously access shared variables.
class ExclusionByMethod {
private int data = 0;
public synchronized void update ( ){
data++;
} }

• Monitor procedures are implemented as synchronized methods.


• Only 1 lock per object in Java
• if a synchronized method is invoked the following occurs:
– it waits to obtain the lock,
– executes the method, and then
– releases the lock.
• This is known as intrinsic locking.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Synchronized statement
• Can also have Mutual exclusion with synchronized statement
in method’s body:
class ExclusionByGroup {
private int data = 0;
public void update ( ){
synchronized (this) { // lock this object for
data++; // the following group of } // statements
} }
• The keyword this refers to object invoking the update method.
• The lock is obtained on the invoking object.
• A synchronized statement specifies that the following group of
• statements is executed as an atomic, non interruptible, action.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
class Callme {
synchronized void call(String msg) {

OUTPUT:
[Hello]
[Synchronized]
[World]

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Alternate way of synchronization
synchronized(object) {
// statements to be synchronized
}

public void run() {


synchronized(target) { // synchronized block
target.call(msg);
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Inter thread communication
• wait( ) tells the calling thread to give up the monitor and go to
sleep 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 the
same object. One of the threads will be granted access.
These methods are declared within Object, as shown here:
• final void wait( ) throws InterruptedException
• final void notify( )
• final void notifyAll( )
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
class Customer{ class Test{
int amount=10000; public static void main(String args[]){
final Customer c=new Customer();
synchronized void withdraw(int amount){ new Thread(){
System.out.println("going to withdraw..."); public void run(){c.withdraw(15000);}
}.start();
if(this.amount<amount){ new Thread(){
System.out.println("Less balance; waiting for public void run(){c.deposit(10000);}
deposit..."); }.start();
try{wait();}catch(Exception e){}
} }}
this.amount-=amount;
System.out.println("withdraw completed...");
} Output: going to withdraw...
synchronized void deposit(int amount){ Less balance; waiting for deposit...
System.out.println("going to deposit..."); going to deposit...
this.amount+=amount; deposit completed...
System.out.println("deposit completed... "); withdraw completed
notify();
}
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Daemon Threads

• Any Java thread can be a daemon thread.


• Daemon threads are service providers for other threads running in the
same process as the daemon thread.
• The run() method for a daemon thread is typically an infinite loop that
waits for a service request. When the only remaining threads in a
process are daemon threads, the interpreter exits. This makes sense
because when only daemon threads remain, there is no other thread
for which a daemon thread can provide a service.
• To specify that a thread is a daemon thread, call the setDaemon
method with the argument true. To determine if a thread is a daemon
thread, use the accessor method isDaemon.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Deadlock

Deadlock is a situation of complete Lock, when no thread


can complete its execution because lack of resources.

Thread Pooling

Pooling is usually implemented by loop i.e to check some condition


repeatedly. Once condition is true appropriate action is taken.
This waste CPU time.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Deadlock
In the picture, Thread 1 is holding a
resource R1, and need another resource
R2 to finish execution, but R2 is locked
by Thread 2, which needs R3, which in
turn is locked by Thread 3. Hence none
of them can finish and are
stuck in a deadlock.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
public class TestDeadlockExample1 { System.out.println
public static void main(String[] args) { ("Thread 2: locked resource 2");
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal"; try { Thread.sleep(100);}
// t1 tries to lock resource1 then resource2 catch (Exception e) {}
Thread t1 = new Thread() {
synchronized (resource1) {
public void run() {
System.out.println
synchronized (resource1) { ("Thread 2: locked resource 1");
System.out.println("Thread 1: locked resource 1"); }
}
try { Thread.sleep(100);} catch (Exception e) {} }
}; //anonymous class
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2"); t1.start();
} t2.start();
} }
} }
};
Output:
// t2 tries to lock resource2 then resource1 Thread 1: locked resource 1
Thread t2 = new Thread() { Thread 2: locked resource 2
_
public void run() {
synchronized (resource2) {

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Difference between wait() and sleep()
wait() sleep()

called from synchronized block no such requirement

monitor is released monitor is not released

awake not awake when notify() or


when notify() or notifyAll() method is notifyAll() method is called
called.

not a static method static method

wait() is generally used on condition sleep() method is simply used to put


your thread on sleep.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Pool and Executor Framework
Java Thread pool represents a group of worker threads that are waiting for the job
and reuse many times.
• In case of thread pool, a group of fixed size threads are created. A thread from the
thread pool is pulled out and assigned a job by the service provider. After
completion of the job, thread is contained in the thread pool again.
Advantage of Java Thread Pool
• Better performance It saves time because there is no need to create new thread.

It contains a work queue which holds tasks waiting to get executed.


– Collection of Runnable objects

• Executors manage thread execution.


• At the top of the executor hierarchy is the Executor interface, which is used to
initiate a thread.

• In the java.util.concurrent package there are three interfaces:


• Executor — Used to submit a new task.
• ExecutorService — A subinterface of Executor that adds methods to manage
lifecycle of threads used to run the submitted tasks and methods to produce a
Future to get a result from an asynchronous computation.
• ScheduledExecutorService — A subinterface of ExecutorService, to
execute commands periodically or after a given delay.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
ExecutorService
• ExecutorService extends Executor and
provides methods that manage execution.
• There are three implementations of
ExecutorService:
– ThreadPoolExecutor,
– ScheduledThreadPoolExecutor,
– ForkJoinPool.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
WorkerThread.java SimpleThreadPool.java
public class WorkerThread implements Runnable import java.util.concurrent.ExecutorService;
{ private String command; import java.util.concurrent.Executors;
public WorkerThread(String s){ public class SimpleThreadPool {
this.command=s; } public static void main(String[] args) {
public void run() { ExecutorService executor =
System.out.println(Thread.currentThread().ge Executors.newFixedThreadPool(5);
tName()+" Start. Command = "+command); for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread(""
processCommand(); + i);
executor.execute(worker);
System.out.println(Thread.currentThread().ge }
tName()+" End."); executor.shutdown();
} while (!executor.isTerminated()) {
private void processCommand() { }
try { System.out.println("Finished all threads");
}
Thread.sleep(5000); }
} catch (InterruptedException e) {
e.printStackTrace(); } }
public String toString(){
return this.command; }}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
C:\Users\Hai...!\Desktop>java SimpleThreadPo
pool-1-thread-2 Start. Command = 1
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-2 End.
pool-1-thread-3 End.
pool-1-thread-2 Start. Command = 5
pool-1-thread-1 End.
pool-1-thread-5 End.
pool-1-thread-4 End.
pool-1-thread-5 Start. Command = 8
pool-1-thread-1 Start. Command = 7
pool-1-thread-3 Start. Command = 6
pool-1-thread-4 Start. Command = 9
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
Finished all threads
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Callable and Future
• Java 5 introduced
java.util.concurrent.Callable interface in concurrency package
• It is similar to Runnable interface but it can return any Object
and able to throw Exception.
• This interface represents a thread that returns a value.
• An application can use Callable objects to compute results
that are then returned to the invoking thread.
• This is a powerful mechanism because it facilitates the coding
of many types of numerical computations in which partial
results are computed simultaneously.
• It can also be used to run a thread that returns a status code
that indicates the successful completion of the thread.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• Java Callable interface use Generic to define
the return type of Object.
• Executor class provides useful methods to
execute Java Callable in a thread pool.
• Since callable tasks run in parallel, we have to
wait for the returned Object

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Future
• Java Callable tasks
return java.util.concurrent.Future object.
• Using Java Future object, we can find out the status of
the Callable task and get the returned Object.
• It provides get() method that can wait
– Indefinitely for the Callable to finish and then return the
result
– Or wait for a specified time for the output
– Else throws exception
• Java Future provides cancel() method to cancel the
associated Callable task
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Fork and Join
• The ForkJoinPool was added to Java in Java 7.
• The ForkJoinPool is similar to the Java
ExecutorService but with one difference.
• The ForkJoinPool makes it easy for tasks to
split their work up into smaller tasks which are
then submitted to the ForkJoinPool .
• Tasks can keep splitting their work into smaller
subtasks for as long as it makes to split up the
task

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
FORK
• A task that uses the fork and join principle can fork (split) itself into
smaller subtasks which can be executed concurrently.

• By splitting itself up into subtasks, each subtask can be executed in parallel


by different CPUs, or different threads on the same CPU.

• A task only splits itself up into subtasks if the work the task was given is
large enough for this to make sense.

• There is an overhead to splitting up a task into subtasks, so for small


amounts of work this overhead may be greater than the speedup achieved
by executing subtasks concurrently.

• The limit for when it makes sense to fork a task into subtasks is also called
a threshold. It is up to each task to decide on a sensible threshold. It
depends very much on the kind of work being done.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Join
• When a task has split itself up into subtasks,
the task waits until the subtasks have finished
executing.
• Once the subtasks have finished executing,
the task may join (merge) all the results into
one result.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
FORK JOIN POOL
• The ForkJoinPool is a special thread pool which is
designed to work well with fork-and-join task splitting.
• located in the java.util.concurrent package, so the full
class name is java.util.concurrent.ForkJoinPool.
• ForkJoinPool is created using its constructor.
• As a parameter to the ForkJoinPool constructor you
pass the indicated level of parallelism you desire.
• The parallelism level indicates how many threads or
CPUs you want to work concurrently on tasks passed to
the ForkJoinPool.
• ForkJoinPool forkJoinPool = new ForkJoinPool(4);

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
LOCK
• A java.util.concurrent.locks.Lock is a thread
synchronization mechanism just
like synchronized blocks.
• A Lock is, however, more flexible and more
sophisticated than a synchronized block.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• First a Lock is created. Then it's lock() method
is called. Now the Lock instance is locked.
• Any other thread calling lock() will be blocked
until the thread that locked the lock
calls unlock().
• Finally unlock() is called, and the Lock is now
unlocked so other threads can lock it.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Difference between Synchronized and
Lock
• A synchronized block makes no guarantees about
the sequence in which threads waiting to
entering it are granted access.
• You cannot pass any parameters to the entry of a
synchronized block. Thus, having a timeout trying
to get access to a synchronized block is not
possible.
• The synchronized block must be fully contained
within a single method. A Lock can have it's calls
to lock() and unlock() in separate methods.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
LOCK METHOD
• The Lock interface has the following primary
methods:
– lock()
– lockInterruptibly()
– tryLock()
– tryLock(long timeout, TimeUnit timeUnit)
– unlock()

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• The lock() method locks the Lock instance if possible. If the Lock instance is already
locked, the thread calling lock() is blocked until the Lock is unlocked.

• The lockInterruptibly() method locks the Lock unless the thread calling the method
has been interrupted. Additionally, if a thread is blocked waiting to lock
the Lock via this method, and it is interrupted, it exits this method calls.

• The tryLock() method attempts to lock the Lock instance immediately. It


returns true if the locking succeeds, false if Lock is already locked. This method
never blocks.

• The tryLock(long timeout, TimeUnit timeUnit) works like the tryLock() method,
except it waits up the given timeout before giving up trying to lock the Lock.

• The unlock() method unlocks the Lock instance. Typically, a Lock implementation
will only allow the thread that has locked the Lock to call this method. Other
threads calling this method may result in an unchecked exception
(RuntimeException)

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Annotation
• Java has supported a feature that enables you to embed supplemental
information into a source file. This information, called an annotation, does
not change the actions of a program. Thus, an annotation leaves the
semantics of a program unchanged.
• The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}

• // A simple annotation type.


@interface MyAnno {
String str();
int val();
}

• Annotation is a super-interface of all annotations. It is declared within the


java.lang.annotation package
• Metadata i.e attached with class, method, interface, or fields to indicate
some additional information which can be used by java compiler or JVM

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Using Annotations
// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth() { // ... }

Annotations can be applied to declarations:


declarations of classes, fields, methods, and other
program elements. When used on a declaration,
each annotation often appears, by convention, on
its own line.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Built-In Annotation

• Built-In Java Annotations used in java code


– @Override
– @SuppressWarnings
– @Deprecated
• Built-In Java Annotations used in other annotations
– @Target
– @Retention
– @Inherited
– @Documented

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Built-in
• @override
– @Override annotation assures that the subclass
method is overriding the parent class method. If it is
not so, compile time error occurs.
• @SuppressWarnings annotation: is used to
suppress warnings issued by the compiler.

• @Deprecated annotation marks that this method


is deprecated so compiler prints warning. It
informs user that it may be removed in the future
versions. So, it is better not to use such methods.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
@depreceated Example
• class A{ At Compile Time:
• void m(){System.out.println("hello m");} Note: Test.java uses or
• overrides a deprecated
• @Deprecated API.
• void n(){System.out.println("hello n");}
• } Note: Recompile with -
• Xlint:deprecation for
• class TestAnnotation3{
details.
• public static void main(String args[]){

• A a=new A(); Anyhow when running
• a.n(); gives output --
• }} hello n

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Types of Custom Annotation
• There are three types of annotations.
– Marker Annotation
– Single-Value Annotation
– Multi-Value Annotation
1) Marker Annotation
• An annotation that has no method, is called marker annotation.
For example:
• @interface MyAnnotation{}
• The @Override and @Deprecated are marker annotations.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• 2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For
example:
@interface MyAnnotation{
int value();
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}
How to apply Single-Value Annotation
@MyAnnotation(value=10)

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Multi-Value Annotation
• 3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For
example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
} }
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}

• How to apply Multi-Value Annotation


• @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Built-in Annotation used in custom
• @Target
@Target tag is used to specify at which type, the
annotation is used.
The java.lang.annotation.ElementType enum declares
many constants to specify the type of element where
annotation is to be applied such as TYPE, METHOD,
FIELD etc

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example
To specify for a class
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
• To specify for class, method, fields
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.M
ETHOD})
@interface MyAnnotation{
int value1();
String value2();
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
@Retention
• @Retention annotation is used to specify to what
level annotation will be available.

RetentionPolicy Availability
RetentionPolicy.SOURCE refers to the source code,
discarded during compilation. It
will not be available in the
compiled class.
RetentionPolicy.CLASS refers to the .class file, available
to java compiler but not to JVM .
It is included in the class file.
RetentionPolicy.RUNTIME refers to the runtime, available to
java compiler and JVM .
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
@Inherited

• By default, annotations are not inherited to subclasses. The


@Inherited annotation marks the annotation to be inherited to
subclasses.

@Inherited
@interface ForEveryone { }//Now it will be available to subclass also

@interface ForEveryone { }
class Superclass{}

class Subclass extends Superclass{}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
@Documented
• @Documented
• The @Documented Marks the annotation for
inclusion in the documentation.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
How to use
public class Generation3List extends Generation2List
{ // Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here }

Adding comment to the code , instead it can be defined as


Annotation

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
After the annotation type is defined, you can use annotations of that
type, with the values filled in, like this:

@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation reviewers = {"Alice", "Bob", "Cindy"} )

public class Generation3List extends Generation2List {


// class code goes here
}

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Using@Documented
• To make the information in @ClassPreamble appear in
Javadoc-generated documentation

• Annotate @ClassPreamble definition with


the @Documented annotation

• // import this to use @Documented


• import java.lang.annotation.*;
• @Documented
• @interface ClassPreamble { // Annotation element
definitions }

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Restrictions – Annotation Method

• There are few points that should be remembered by the


programmer.
• Method should not have any throws clauses
• Method should return one of the following: primitive data
types, String, Class, enum or array of these data types.
• Method should not have any parameter.
• We should attach @ just before interface keyword to define
annotation.
• It may assign a default value to the method.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Enum
• Enum in java is a data type that contains fixed
set of constants.
• It can be used for days of the week (SUNDAY,
MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc.
• The java enum constants are static and final
implicitly.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);
}}

• Can be Defined outside class or inside the Class

enum Season { WINTER, SPRING, SUMMER, FALL }

class EnumExample2{
public static void main(String[] args) {
Season s=Season.WINTER;
System.out.println(s);
}}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
// Use the built-in enumeration methods. System.out.println();
// An enumeration of apple varieties. // use valueOf()
enum Apple ap = Apple.valueOf("Winesap");
{ Jonathan, GoldenDel, RedDel, System.out.println("ap contains " + ap);
Winesap, Cortland } }}
class EnumDemo2 { output
public static void main(String args[]) { Here are all Apple constants: Jonathan
Apple ap; GoldenDel
System.out.println("Here are all Apple RedDel
constants:");
Winesap
// use values()
Cortland
Apple allapples[] = Apple.values();
for(Apple a : allapples) ap contains Winesap
System.out.println(a);

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6

You might also like