Java
Java
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
VirtualMachineError
Error
AWTError
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
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
VirtualMachineError
Error
AWTError
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Checked Exceptions vs. Unchecked
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
VirtualMachineError
Error Unchecked
exception.
AWTError
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Declaring, Throwing, and Catching
Exceptions
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.
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,
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
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).
(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
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
Next statement;
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
animation
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
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
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Reasons for Multi-Threading
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
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...");
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Creating Threads
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Methods
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 1
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
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example: New Thread 1
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Synchronization
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread Synchronization
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++;
} }
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
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Daemon Threads
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Deadlock
Thread Pooling
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()
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.
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.
• A task only splits itself up into subtasks if the work the task was given is
large enough for this to make sense.
• 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(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{}
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() { // ... }
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Built-In Annotation
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.
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";
}
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
@Inherited
@interface ForEveryone { }//Now it will be available to subclass also
@interface ForEveryone { }
class 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 }
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"} )
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Restrictions – Annotation 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 }
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