0% found this document useful (0 votes)
2 views

Unit 4

The document outlines the course objectives and learning outcomes for a Java Programming course at Pimpri Chinchwad University, focusing on fundamental concepts, object-oriented principles, exception handling, multithreading, and JDBC connectivity. It details key concepts of multithreading, including thread life cycles, advantages, and inter-thread communication, as well as types of JDBC drivers and the Data Access Object (DAO) design pattern. The course aims to equip students with practical skills for developing software applications using Java.

Uploaded by

bhayu773
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)
2 views

Unit 4

The document outlines the course objectives and learning outcomes for a Java Programming course at Pimpri Chinchwad University, focusing on fundamental concepts, object-oriented principles, exception handling, multithreading, and JDBC connectivity. It details key concepts of multithreading, including thread life cycles, advantages, and inter-thread communication, as well as types of JDBC drivers and the Data Access Object (DAO) design pattern. The course aims to equip students with practical skills for developing software applications using Java.

Uploaded by

bhayu773
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
You are on page 1/ 34

1

PCET’S Pimpri Chinchwad University

Department of Computer Science and Engineering


Course Name : Java Programming
Course Code/Course Type : UBTCE212/PCC
SY. B.Tech

Prepared By: Mr. Chandan Prasad

PIMPRI CHINCHWAD UNIVERSITY


2

Course Objectives (CO):


• The objectives of Java Programming are:
To learn the fundamentals of the Java programming language.
To learn object-oriented principles like abstraction, encapsulation,
inheritance, and polymorphism and apply them in solving problems using
java.
To apply the concepts of exception handling, multithreading and collection
classes using java.

To develop software applications using JDBC connectivity.


To design the Graphical User Interface using applets and swing controls.
PIMPRI CHINCHWAD UNIVERSITY
3

Course Learning Outcomes (CLO):


• Students would be able to:
To grasp the fundamentals programming concepts of Java programming
language.

To apply object-oriented principles like abstraction, encapsulation,


inheritance, polymorphism in solving problems using java.
To perform exception handling, multithreading code using java.
To develop software applications using JDBC connectivity.
To design the Graphical User Interface using event handling.

PIMPRI CHINCHWAD UNIVERSITY


UNIT- IV
Multithreading and JDBC
Connectivity
Multithreading

Multithreading in Java is a Threads are beneficial


mechanism that allows because they enable
multiple threads (smaller efficient utilization of CPU
units of execution) to run resources, resulting in
concurrently within a single faster, more responsive,
process. and scalable applications.
Key Concepts: Thread

A thread is a lightweight subprocess and the smallest unit of


execution.

Every Java program has at least one thread (the main thread).
Advantages of Multithreading:

Improved performance due to concurrent execution.

Better CPU utilization by keeping idle time minimal.

Enhanced responsiveness in user interface applications.

Parallelism: Ability to execute tasks simultaneously.


Key Concepts: Process vs. Thread

Process: A heavyweight unit with its own memory space.

Thread: Shares memory space with other threads in the same


process, making threads lighter and faster to start and manage.
Multiple processes and multiple threads:
Aspect Multiple Processes Multiple Threads
Independent executing programs running Lightweight units executing concurrently within a
Definition
separately in their own memory space. single process, sharing memory.
Threads within the same process share memory
Memory Each process has its own memory space.
space.
Uses Inter-Process Communication (IPC)
Directly communicates via shared memory
Communication methods (e.g., pipes, sockets, shared memory,
variables, requiring synchronization.
message queues).
High overhead; separate allocation of memory Low overhead; threads share resources and
Resource Overhead
and resources for each process. memory.
Startup Time Slower; processes take more time to start. Faster; threads can be started quickly.
More expensive due to separate memory Less expensive; threads have shared memory
Context Switching
spaces and resources. context.
Higher; failure in one process usually doesn’t Lower; failure in one thread can potentially crash
Fault Tolerance
affect others. the entire process.
Easier to manage, but synchronization required
Complexity Relatively complex to manage and synchronize.
to avoid race conditions.
Web browsers, operating systems (running Server-side applications handling multiple user
Example Usage
multiple apps simultaneously). requests concurrently, GUI applications.
Thread Life Cycle
A Java thread can be in one of the following states:

New: Thread instance is created but not yet started.

Runnable: Thread is ready or running.

Blocked/Waiting: Thread is waiting for resources or conditions.

Timed Waiting: Waiting for a specified amount of time.

Terminated: Thread has completed execution.


Thread Life Cycle
A Java thread can be in one of the following states:
New: Student enrolled but hasn't attended class yet.

Runnable: Student is attending classes or ready and waiting to enter the


classroom.

Blocked/Waiting: Student waiting indefinitely (classroom occupied by another


lecture).

Timed Waiting: Student waiting for a defined time (scheduled break between
lectures).

Terminated: Student graduated and left the university


Thread Life Cycle
Thread thread = new Thread();

thread.start();

Thread.sleep(5000);

obj.wait(1000);
Thread t1 = new Thread(()
-> {
// task
});
synchronized(object) { BLOCKED. } synchronized(obj){ t1.start();
obj.wait();} t1.join();
Creating Threads in Java:Extending the Thread
Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running by extending Thread class.");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread
}
}
Creating Threads in Java:Implementing the
Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running by implementing Runnable interface.");
}
}

public class Main {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start(); // starts the thread
}
}
Thread Priority

• In Java, Thread Priority determines the order in which threads are


scheduled for execution.

• Thread priority is represented by an integer value ranging between


1 (MIN_PRIORITY) and 10 (MAX_PRIORITY), with 5
(NORM_PRIORITY) being the default priority
How to Set Thread Priority
• Use the setPriority() method to set
thread priority

Priority Constant Value


MIN_PRIORITY 1
Thread t = new Thread();
NORM_PRIORITY 5 t.setPriority(Thread.MAX_PRIORITY
MAX_PRIORITY 10 ); // sets highest priority (10)
How Thread Scheduler Uses Priority

• Threads with higher priorities are generally given preference by the


JVM scheduler.

• However, priority doesn’t guarantee exact execution order—it only


influences the likelihood of selection by scheduler.

• The scheduling depends on the JVM and underlying OS, meaning


results can vary.
How Thread Scheduler Uses Priority

• Threads with higher priorities are generally given preference by the


JVM scheduler.

• However, priority doesn’t guarantee exact execution order—it only


influences the likelihood of selection by scheduler.

• The scheduling depends on the JVM and underlying OS, meaning


results can vary.
How Thread Scheduler Uses Priority

• Threads with higher priorities are generally given preference by the


JVM scheduler.

• However, priority doesn’t guarantee exact execution order—it only


influences the likelihood of selection by scheduler.

• The scheduling depends on the JVM and underlying OS, meaning


results can vary.
Default Priority
• If you don’t explicitly set priority, Java assigns NORM_PRIORITY (value 5) by
default.

• System.out.println(Thread.currentThread().getPriority()); // typically outputs 5


Interthread Communication in Java

• Interthread communication is a mechanism in Java that enables


multiple threads to coordinate their actions by communicating with
each other.

• This communication ensures threads operate in harmony without


conflicting or duplicating each other's tasks.
Why is Interthread Communication
Needed?
• To manage the order and coordination of threads.

• To prevent threads from continuously checking conditions (busy


waiting), thereby improving efficiency.

• To share data safely between threads.
Key Methods for Interthread
Communication

Method Description
Causes the current thread to wait indefinitely until another
wait()
thread calls notify() or notifyAll()
notify() Wakes up one waiting thread on the same object’s monitor
notifyAll() Wakes up all waiting threads on the object’s monitor
Simple Workflow

1. Producer produces data, signals Consumer using notify().

2. Consumer waits for data using wait().

3. Communication occurs within a shared synchronized object.


Real-Life Analogy

Think about a simple restaurant kitchen scenario:


•Chef (Producer) cooks dishes, places them on a table.
•Waiter (Consumer) picks up dishes and serves customers.

Communication:
•Waiter waits until the dish is ready (wait).
•Chef notifies waiter as soon as the dish is ready (notify).
JDBC Drivers Overview

Platform
Type Name Description Performance
Dependency
JDBC-ODBC
1 Uses ODBC drivers Dependent Lowest
Bridge
Native API Converts JDBC calls into
2 Dependent Moderate
Driver native API
Middleware
Network
3 communicates via Independent Good
Protocol
network
Direct Java-based
4 Thin Driver Independent Best
communication
Type 1: JDBC-ODBC Bridge Driver

•Converts JDBC calls into ODBC calls.

•Platform dependent (requires ODBC installation).

•Deprecated and no longer widely used (removed in JDK 8 onwards).

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DataSourceName", "user", "password");
Type 2: Native API Driver

•Translates JDBC calls to native database calls (using vendor libraries).

•Platform dependent, requires installation of native DB libraries.

•Better performance than Type 1.

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:oci:@databaseName", "user", "password");
Type 3: Network Protocol Driver (Middleware Driver)

•Sends JDBC calls to a middleware server that translates calls into


database-specific protocol.

•Platform independent.

•Middleware adds overhead but allows flexible deployment and multiple


databases connections.

Class.forName("com.ids.jdbc.IDSDriver");
Connection con = DriverManager.getConnection("jdbc:ids://host:port/dbname", "user", "password");
Type 4: Thin Driver (Pure Java Driver)

•Converts JDBC calls directly into database-specific network protocol.

•Platform independent, entirely Java-based.

•Recommended, highest performance, and most widely used today.

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");

File → Project Structure → Modules → Dependencies tab → (+) button → JARs or


directories
Data Access Objects (DAO)
• Data Access Object (DAO) is a widely-used design pattern in software
development. It abstracts and encapsulates all access to the database or data
source, simplifying data management.

Why to use DAO?


• Separates your database logic from business logic.
• Makes code easier to maintain, test, and modify.
• Simplifies changing data storage mechanisms (e.g., switch from MySQL to
Oracle) without impacting the application logic.
Structure of DAO
•DAO Interface:
Declares standard methods for database operations:
•insert()
•update()
•delete()
•get() or select()

•DAO Implementation Class:


Implements these interface methods and contains actual JDBC/database
code.

•Data Transfer Object (DTO)/Model Class (optional but common):


Represents data objects passed between the DAO and other layers.
DAO vs JDBC Driver (Type 4)

DAO (Data Access Object) JDBC Driver (Type-4)


It’s an actual library
It's a design pattern
(implementation)
Actually communicates with the
Organizes your Java code
database
Independent of database specifics Database-specific connection
(at the code-level) handling
High-level abstraction High-level abstraction

You might also like