0% found this document useful (0 votes)
4 views13 pages

Unit 4 Multithreading in Java

The document provides an overview of Java Beans, multithreading, JDBC, Java networking, collections, and exception handling in Java. It explains the structure and properties of Java Beans, the concept of multithreading and thread synchronization, how to connect to databases using JDBC, and the Java Collections Framework. Additionally, it covers networking concepts and exception handling mechanisms in Java, including examples and code snippets for better understanding.

Uploaded by

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

Unit 4 Multithreading in Java

The document provides an overview of Java Beans, multithreading, JDBC, Java networking, collections, and exception handling in Java. It explains the structure and properties of Java Beans, the concept of multithreading and thread synchronization, how to connect to databases using JDBC, and the Java Collections Framework. Additionally, it covers networking concepts and exception handling mechanisms in Java, including examples and code snippets for better understanding.

Uploaded by

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

Unit IV-Multithreading in java:

Java Beans Definition:

A Java Bean is a simple Java class that follows specific rules:


- It has private variables (data members).
- It provides public getter and setter methods to access and update the variables.
- It has a public no-argument constructor.

Java Beans are mainly used to store and transfer data in Java programs, especially in web applications.

Properties of Java Bean:

1. Private Variables – Data members are declared private to ensure data protection (encapsulation).
2. Public No-Argument Constructor – Allows easy object creation.
3. Getter Methods – Used to read the value of private variables.
4. Setter Methods – Used to change the value of private variables.
5. Serializable (Optional) – Java Beans can be serialized for storage or transfer over networks.

Advantages of Java Bean:

1. Reusable – Can be reused across multiple programs.


2. Encapsulation – Keeps data safe using private access.
3. Easy to Transfer Data – Useful in passing data between layers (UI to backend).
4. Simple Structure – Easy to understand and maintain.
5. Readable and Maintainable – Well-organized code.
6. Supports Tools and Frameworks – Works smoothly with JSP, Spring, etc.
7. Easy Object Creation – With the no-arg constructor.

Simple Example:

public class Student {


// Private variables
private String name;
// Public no-argument constructor
public Student() {
// Constructor body
}
// Getter for name
public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
[Link] = name;
}
}
Usage Example (Test Class):

public class TestStudent {


public static void main(String[] args) {
Student s1 = new Student();
[Link]("John");
[Link]("Name: " + [Link]());
}
}

Note:

Java Beans are platform-independent because they are written in Java, and Java is platform-independent due to the
JVM (Java Virtual Machine).

Multithreading

The process of executing multiple tasks (also called threads) simultaneously is called multithreading. A
multithreaded program contains two or more parts that can run concurrently.

Java Threads

Threads allows a program to operate more efficiently by doing multiple things at the same time.

Threads can be used to perform complicated tasks in the background without interrupting the main program.

Creating a Thread

There are two ways to create a thread.

1. It can be created by extending the Thread class:

Syntax:

public class Main extends Thread {

public void run() {

[Link]("This code is running in a thread");

}}

Program:

public class Main extends Thread {

public void run() {

[Link]("This code is running in a thread");

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

Main ob = new Main();

[Link]();

[Link]("This code is outside of the thread");

2. Another way to create a thread is to implement the Runnable interface:

Java runnable is an interface used to execute code on a concurrent thread. It is an interface which is
implemented by any [Link] runnable interface has an undefined method run() with void as return type, and it
takes in no arguments.

Syntax:

public class Main implements Runnable {

public void run() {

[Link]("This code is running in a thread");

}}

Program

public class Main implements Runnable {

public void run() {

[Link]("This code is running in a thread");

public static void main(String[] args) {

Main obj = new Main();

Thread thread = new Thread(obj);

[Link]();

}
Thread Life cycle:
1. New.
2. Runnable.
3. Running.
4. Blocked(Non-Runnable).
5. Terminated/Dead.

New:A thread is in this state when it is created but not yet started using start() method.

Runnable:After calling start(), the thread becomes Runnable and is eligible to run.

Running

The thread is actively executing. The JVM thread scheduler selects it from the runnable pool.

Blocked (Non-Runnable)

The thread is alive but not eligible to run. It may be waiting for a resource (like I/O or a lock).

Terminated (Dead)

A thread enters this state when it completes execution normally or abruptly (e.g., due to an exception).

Thread synchronization:

Thread synchronization in Java is important for managing shared resources in a multithreaded environment. It
ensures that only one thread can access a shared resource at a time, which enhances the overall system performance
and prevents race conditions and data corruption.

Why is Thread Synchronization Important?

In a multithreaded environment, threads may compete for shared resources i.e. files, memory, etc. Without
synchronization, simultaneous access can lead

Race Conditions: Multiple Threads interchanging shared data at the same time and it results an unpredictable output.
Data Corruption: Incomplete or corrupted data when multiple threads modify the same resource simultaneously.

Thread synchronization can be achieved by

1. Synchronized Method

We can declare a method as synchronized using the synchronized keyword. This will make the code written inside
the method thread-safe so that no other thread will execute while the resource is shared.

2. Synchronized Block

If we declare a block as synchronized, only the code which is written inside that block is executed sequentially not
the complete code. This is used when we want sequential access to some part of code or to synchronize some part of
code.

Syntax

synchronized (object reference)


{
// Insert code here
}

3. Static Synchronization

In this, the synchronized method is declared as “static” which means the lock or monitor is applied on the class not
on the object so that only one thread will access the class at a time.

JDBC (Java Database Connectivity)

Introduction to JDBC
JDBC stands for Java Database Connectivity.
It is an API (Application Programming Interface) in Java that allows Java programs to interact with databases.
JDBC helps in connecting to a database, sending SQL queries, and retrieving results.

JDBC is an API that helps applications to communicate with databases, it allows Java programs to connect to a
database, run queries, retrieve, and manipulate data. Because of JDBC, Java applications can easily work with
different relational databases like MySQL, Oracle, PostgreSQL, and more.

JDBC Architecture
Types of JDBC Drivers
 JDBC drivers are used to connect Java applications to the database. There are 4 types:

 Application: It can be a Java application or servlet that communicates with a data source.

 The JDBC API: It allows Java programs to execute SQL queries and get results from the database.

 DriverManager uses JDBC drivers to help Java applications connect and communicate with databases.

Type Name Description

Type 1 JDBC-ODBC Bridge Connects using ODBC


Driver driver; now obsolete.

Type 2 Native-API Driver Converts JDBC calls into


native calls of the DB.

Type 3 Network Protocol Driver Sends JDBC calls to a


middleware server.

Type 4 Thin Driver (Pure Java) Directly connects to the


database using pure Java;
commonly used.

✅ Type 4 driver is used for Oracle, MySQL, etc.

Steps to Connect to Oracle Database Using JDBC

Step 1: Import JDBC Package


import [Link].*;

Step 2: Load the JDBC Driver


[Link]("[Link]");
Step 3: Establish a Connection
Connection con = [Link](
"jdbc:oracle:thin:@localhost:1521:xe",
"your_username",
"your_password"
);

Step 4: Create a Statement


Statement stmt = [Link]();

Step 5: Execute a Query


ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
[Link]("ID: " + [Link]("id") + ", Name: " + [Link]("name"));
}

Step 6: Close the Connection


[Link]();
[Link]();
[Link]();

Java program that demonstrates how to connect to an Oracle database using JDBC, create a table, insert records, and
retrieve data.
Java Code

import [Link].*;

public class OracleDBExample {


public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link](
"jdbc:oracle:thin:@localhost:1521:xe", "your_username", "your_password");
Statement stmt = [Link]();

[Link]("CREATE TABLE students (id NUMBER PRIMARY KEY, name


VARCHAR2(50))");
[Link]("INSERT INTO students VALUES (101, 'John Doe')");
[Link]("INSERT INTO students VALUES (102, 'Jane Smith')");

ResultSet rs = [Link]("SELECT * FROM students");


while ([Link]()) {
[Link]("ID: " + [Link]("id") + ", Name: " + [Link]("name"));
}

[Link](); [Link](); [Link]();


} catch (Exception e) {
[Link]("Error: " + e);
}
}
}

Java Networking

What is Networking in Java?


Java Networking is the concept of connecting two or more computing devices for sharing resources. Java provides
the [Link] package to support networking.

Important Networking Terms


Term Description
IP Address A unique number assigned to each device
on a network (e.g., [Link])
Port Number A 16-bit number (0–65535) that identifies
a specific process or service
Protocol A set of rules to send and receive data
(e.g., TCP, UDP)
Socket An endpoint for communication between
two machines
Client The machine or program that requests
data
Server The machine or program that responds to
requests

Advantages of Java Networking


 Platform-independent communication
 Easy to implement client-server applications
 Built-in support via [Link] package

Java Networking Classes in [Link] Package


Class Description
InetAddress Represents an IP address
Socket Used by client to connect to server
ServerSocket Used by server to listen for clients
DatagramSocket Used for UDP communication
URL Represents a Uniform Resource Locator

What is Socket Programming?


Socket programming allows communication between two machines (client and server) over a network. It is the
foundation of network applications such as chat apps, web browsers, file transfers, etc.

What is a Socket?
A Socket is an endpoint for sending or receiving data across a computer network.

 The client uses a Socket to connect to the server.


 The server uses a ServerSocket to listen and accept connections.

Key Java Classes for Socket Programming


Class Purpose
Socket Connects to a server
ServerSocket Waits for and accepts client connections
DataInputStream Reads data sent over socket
DataOutputStream Sends data over socket

Java Collections

What is Java Collections Framework?


The Java Collections Framework is a set of classes and interfaces in the [Link] package that helps in storing,
managing, and processing groups of objects efficiently.

It includes lists, sets, maps, and queues, which allow dynamic memory allocation, built-in sorting, searching, and
modification of data.

ArrayList in Java

Definition:
ArrayList is a class in the Collections Framework that implements the List interface using a dynamic array.
It grows or shrinks automatically as elements are added or removed.
Features:
- Fast access (uses index numbers).

- Slower for insertions/deletions in the middle (requires shifting elements).

- Allows duplicate elements and maintains insertion order.

Example:

import [Link];
class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link](list);
}
}

ArrayList Operations
1. add(element) – Adds an element to the list.

2. add(index, element) – Inserts an element at a specific position.

3. get(index) – Retrieves the element at the specified index.

4. set(index, element) – Replaces the element at the specified index.

5. remove(index) – Removes the element at the specified index.

6. size() – Returns the number of elements in the list.

7. contains(element) – Checks if the list contains a particular element.

8. clear() – Removes all elements from the list.

Example:

ArrayList<String> list = new ArrayList<>();


[Link]("Red");
[Link]("Blue");
[Link](1, "Green");
[Link]([Link](1)); // Output: Green
[Link](2);
[Link](list);

Definition:
LinkedList is a class that implements the List and Deque interfaces using a doubly linked list.
Each element (called a node) contains data and links to the next and previous nodes.
Features:
- Slower access (no direct index access like an array).

- Fast insertions and deletions, especially at the beginning or middle.

- Maintains insertion order and allows duplicate values.

Example:

import [Link];
class Example {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
[Link]("Cat");
[Link]("Dog");
[Link](list);
}
}

LinkedList Operations
1. add(element) – Adds an element at the end.

2. addFirst(element) – Adds an element at the beginning.

3. addLast(element) – Adds an element at the end (same as add()).

4. get(index) – Retrieves the element at a specific index.

5. remove(index) – Removes the element at a specified index.

6. removeFirst() – Removes the first element.

7. removeLast() – Removes the last element.

8. size() – Returns the number of elements in the list.

Exception Handling Mechanism

Definition: An exception is an event, which occurs during the execution of a program,


that disrupts the normal flow of the program's instructions.

Or

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors
so that the normal flow of the application can be maintained.
Java Exception Keywords

Java provides keywords that are used to handle the exception. The following table describes each.

Keyword Description

The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch
Try
or finally.

The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
Catch

The "finally" block is used to execute the necessary code of the program. It is executed
Finally
whether an exception is handled or not.

Throw The "throw" keyword is used to throw an exception.

Syntax for try-catch-finally

try

catch(Exception e)

finally

}
Example:

public class JavaExceptionExample {

public static void main(String args[]) {

try {

int data = 100 / 0;

} catch (ArithmeticException e) {

[Link](e);

} finally {

[Link]("Program continues"); }

Output:[Link]: / by zero

Program continues

You might also like