0% found this document useful (0 votes)
7 views10 pages

Java Packages, Threads, and Exception Handling

The document provides an overview of Java packages, exception handling, threads, and inter-thread communication. It explains the purpose of packages in organizing code, the mechanics of exception handling, and the lifecycle and synchronization of threads. Additionally, it covers messaging between threads, the Runnable interface, and the concept of deadlock in Java.

Uploaded by

manodeepak145
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views10 pages

Java Packages, Threads, and Exception Handling

The document provides an overview of Java packages, exception handling, threads, and inter-thread communication. It explains the purpose of packages in organizing code, the mechanics of exception handling, and the lifecycle and synchronization of threads. Additionally, it covers messaging between threads, the Runnable interface, and the concept of deadlock in Java.

Uploaded by

manodeepak145
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

A package in Java is a mechanism to group related classes, interfaces, and sub-packages into a

single unit. Packages help organize large applications, avoid naming conflicts, provide access
protection, and make code modular and maintainable.
 Avoiding name conflicts (two classes with the same name can exist in different
packages)
 Providing access control using public, protected, and default access
 Reusability: packaged code can be imported and used anywhere
 Encouraging modular programming
Types of Java Packages

1. Built-in Packages
Built-in Packages comprise a large number of classes that are part of the Java API. Some of the
commonly used built-in packages are:
 [Link]: Contains language support classes(e.g, classes that define primitive data
types, math operations). This package is automatically imported.
 [Link]: Contains classes for supporting input/output operations.
 [Link]: Contains utility classes that implement data structures such as Linked Lists
and Dictionaries, as well as support for date and time operations.
 [Link]: Contains classes for creating Applets.
 [Link]: Contains classes for implementing the components for graphical user
interfaces
User-defined Packages
User-defined Packages are the packages that are defined by the user.
Example:
package [Link];

public class Helper {


public static void show() {
[Link]("Hello from Helper!");
}
}
To use it in another class:
import [Link];

public class Test {


public static void main(String[] args) {
[Link]();
}
}
Accessing Classes Inside a Package
In Java, we can import classes from a package using either of the following methods:
1 Import a Single Class
import [Link];
This imports only the Vector class from the [Link] package.
2. Import all classes from a package:
import [Link].*;
This imports all classes and interfaces from the [Link] package but does not include sub-
packages.
INTERFACE

An Interface in Java is an abstract type that defines a set of methods a class must implement. A
class can extend another class and similarly, an interface can extend another interface.
However, only a class can implement an interface and the reverse (an interface implementing a
class) is not allowed.
Java Exception Handling

In Java, exception handling is a mechanism to handle runtime errors, allowing the normal flow
of a program to continue. Exceptions are events that occur during program execution that
disrupt the normal flow of instructions.
Basic try-catch Example
 The try block contains code that might throw an exception,
 The catch block handles the exception if it occurs.
Finally Block
The finally block always executed whether an exception is thrown or not. The finally is used
for closing resources like db connections, open files and network connections, It is used after a
try-catch block to execute code that must run.
throw and throws Keywords
1. throw: Used to explicitly throw a single exception. We use throw when something goes
wrong (or “shouldn’t happen”) and we want to stop normal flow and hand control to exception
handling.
2. throws: Declares exceptions that a method might throw, informing the caller to handle them.
It is mainly used with checked exceptions (explained below). If a method calls another method
that throws a checked exception, and it doesn’t catch it, it must declare that exception in
its throws clause.

Java Exception Hierarchy


In Java, all exceptions and errors are subclasses of the Throwable class. It has two main
branches
1. Exception.
2. Error
Java Threads
A Java thread is the smallest unit of execution within a program. It is a lightweight subprocess
that runs independently but shares the same memory space as the process, allowing multiple
tasks to execute concurrently.
Create Threads in Java
 Extending Thread Class
 Implementing a Runnable interface
1. By Extending Thread Class
Create a class that extends Thread. Override the run() method, this is where you put the code
that the thread should execute. Then create an object of your class and call the start() method.
This will internally call run() in a new thread.
2. Using Runnable Interface
Create a class that implements Runnable. Override the run() method, this contains the code for
the thread. Then create a Thread object, pass your Runnable object to it and call start().
Life Cycle of a Thread
During its thread life cycle, a Java thread transitions through several states from creation to
termination.
 New State
 Runnable State
 Blocked State
 Waiting State
 Timed Waiting State
 Terminated State
Running Threads in Java
There are two methods used for running Threads in Java:
 run() Method: Contains the code for the thread. Calling it directly behaves like a
normal method call.
 start() Method: Launches a new thread and internally calls run() concurrently.
Synchronization in Java
Synchronization in Java is a mechanism that ensures that only one thread can access a shared
resource (like a variable, object, or method) at a time. It prevents concurrent threads from
interfering with each other while modifying shared data.
1. Synchronized Methods
A synchronized method ensures that only one thread can execute it at a time on the same object
instance
2. Synchronized Blocks
Instead of synchronizing an entire method, Java allows synchronization on specific blocks of
code. This improves performance by locking only the necessary section.
3. Static Synchronization
Static synchronization is used to synchronize static methods. In this case, the lock is placed on
the class object rather than the instance.

Messaging in Java

Definition

Messaging in Java refers to the mechanism by which threads communicate and coordinate
with each other during execution. It is mainly implemented using inter-thread communication
methods provided by the Object class. Messaging allows threads to exchange information and
control execution order without busy waiting.

Need for Messaging

 To coordinate multiple threads


 To avoid race conditions
 To implement problems like Producer–Consumer
 To ensure efficient CPU utilization

Messaging Mechanism in Java

Java supports messaging through the following methods of the Object class:
1. wait()
2. notify()
3. notifyAll()

These methods must be called from a synchronized block or method.

Methods Used in Messaging

1. wait()

 Causes the current thread to release the lock and wait until notified
 Thread enters waiting state

[Link]();

2. notify()

 Wakes up one waiting thread

[Link]();

3. notifyAll()

 Wakes up all waiting threads

[Link]();

Working Principle

 One thread sends a message and waits using wait()


 Another thread receives the message and calls notify()
 Waiting thread resumes execution

Advantages

 Avoids busy waiting


 Efficient thread coordination
 Improves performance in concurrent applications
Limitations

 Must be used inside synchronized context


 Improper use can cause deadlock

Applications

 Producer–Consumer problem
 Multithreaded servers
 Real-time systems

Runnable Interface in Java

The Runnable interface in Java is used to create a thread by defining a task that can be
executed concurrently. It contains a single abstract method called run(). A class that
implements Runnable must provide the implementation of this method. The thread execution
begins when the start() method of the Thread class is called, which internally invokes the
run() method.

Runnable is preferred over extending the Thread class because Java does not support
multiple inheritance. By implementing Runnable, a class can extend another class and still
perform multithreaded operations. This approach also separates the task logic from the thread
management, leading to better object-oriented design.

To create a thread using Runnable, a class implements the Runnable interface and overrides
the run() method. An object of this class is then passed to a Thread constructor, and the
start() method is invoked to begin execution.

Example:

class MyTask implements Runnable {


public void run() {
[Link]("Thread running using Runnable");
}
}

class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyTask());
[Link]();
}
}

The advantages of the Runnable interface include support for multiple inheritance, improved
code reusability, flexibility, and the ability to share the same Runnable object among
multiple threads. It is widely used in multithreaded applications such as servers, background
tasks, and real-time systems.

In conclusion, the Runnable interface provides a simple, efficient, and flexible way to
implement multithreading in Java and is generally preferred over extending the Thread class.

Inter-Thread Communication in Java

Inter-thread communication is a mechanism by which multiple threads communicate with each


other to coordinate their execution. In Java, this is achieved using the methods of the Object
class: wait(), notify(), and notifyAll().

Need for Inter-Thread Communication

 To avoid busy waiting.


 To synchronize actions between threads.
 To share resources safely (Producer–Consumer problem).
Methods Used

All these methods belong to the Object class and must be called from a synchronized context.

1. wait()
o Causes the current thread to release the lock and go into waiting state.
o It waits until another thread calls notify() or notifyAll().
2. notify()
o Wakes up one waiting thread.
3. notifyAll()
o Wakes up all waiting threads.

Working Principle

 A thread enters a synchronized block.


 If the condition is not met, it calls wait() and releases the lock.
 Another thread changes the condition and calls notify() / notifyAll().
 The waiting thread resumes execution after acquiring the lock again.

Important Rules

 wait(), notify(), notifyAll() must be called inside synchronized methods or blocks.


 They act on the object’s monitor (lock), not on threads.
 Use notifyAll() when multiple threads are waiting.

Advantages

 Efficient CPU utilization.


 Avoids unnecessary polling.
 Ensures proper synchronization.

Deadlock in Java
Deadlock is a situation where two or more threads are permanently blocked because each thread
is waiting for a resource held by another thread.

Conditions for Deadlock

1. Mutual Exclusion – Resource cannot be shared.


2. Hold and Wait – Thread holds one resource and waits for another.
3. No Preemption – Resource cannot be forcibly taken.
4. Circular Wait – Circular chain of threads waiting for resources.

Suspending, Resuming, and Stopping Threads in Java

These operations control the execution of threads. The methods suspend(), resume(), and stop()
belong to the Thread class but are deprecated because they can cause deadlock and inconsistent
states.

1. Suspending a Thread

 Temporarily pauses a thread.


 Method: suspend() (deprecated)

2. Resuming a Thread

 Restarts a suspended thread.


 Method: resume() (deprecated)

3. Stopping a Thread

 Terminates a thread completely.


 Method: stop() (deprecated)

You might also like