0% found this document useful (0 votes)
21 views44 pages

4 Multi Threading and JDBC

The document provides an overview of multithreading and JDBC in Java. It explains the differences between process-based and thread-based multitasking, the lifecycle of a thread, and methods for thread management, synchronization, and inter-thread communication. Additionally, it covers JDBC architecture, types of JDBC drivers, and the steps to connect a Java application with a database using JDBC.

Uploaded by

pavanisajjana18
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)
21 views44 pages

4 Multi Threading and JDBC

The document provides an overview of multithreading and JDBC in Java. It explains the differences between process-based and thread-based multitasking, the lifecycle of a thread, and methods for thread management, synchronization, and inter-thread communication. Additionally, it covers JDBC architecture, types of JDBC drivers, and the steps to connect a Java application with a database using JDBC.

Uploaded by

pavanisajjana18
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/ 44

Multi Threading

Introduction
The process of executing multiple tasks simultaneously is called
Multitasking. We use multitasking to utilize the CPU.

Multitasking can be achieved in two ways:


1) Process-based Multitasking (Multiprocessing)
2) Thread-based Multitasking (Multithreading)

2
Introduction
Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each
process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the processes is high.
Switching from one process to another requires some time for
saving and loading registers, memory maps, updating lists, etc.
Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the threads is low.
Switching from one thread to another requires very less time.
3
Introduction
Multithreading in Java
Multithreading in java is a process of executing multiple threads
simultaneously.
A Thread is a lightweight sub-process, the smallest unit of
processing.
We use multithreading than multiprocessing because threads use
a shared memory area. They don't allocate separate memory area
so saves memory, and context-switching between the threads
takes less time than process.
Java Multithreading is mostly used in games, animation, etc.

4
Java Thread Model
A Thread is a lightweight
subprocess, the smallest
unit of processing.
Threads are independent.
If there occurs exception
in one thread, it doesn't
affect other threads.
They use a shared memory area.
As shown in the figure,
a thread is executed inside the
process. There is context-switching
between the threads. There can be
multiple processes inside the OS,
and one process can have multiple threads.
5
Java Thread Model
Threads running in parallel does not really mean that they
actually run at the same time.

Since all the threads are running on a single processor, the flow
of execution is shared between the threads.

The Java Interpreter handles the switching of control between the


threads in such a way that it appears they are running
concurrently.

Multithreading is a powerful mechanism that makes java


different from other programming languages.
6
Life cycle of a Thread

State
Transition
diagram
of a
Thread

7
Life cycle of a Thread
1) New
The thread is in new state if you create an instance of Thread class
but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not
eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
8
Creating a Thread
There are two ways to create a thread:
1) By extending Thread class
2) By implementing Runnable interface.
If we start a thread twice, it generates IllegalThreadStateException.
If we call run method directly, context switching doesn't take place.
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and
implements Runnable interface.
Commonly used Constructors of Thread class:
◆ Thread()
◆ Thread(String name)
◆ Thread(Runnable r)
◆ Thread(Runnable r,String name)
9
Thread Scheduler
Thread scheduler in java is the part of the JVM that decides which
thread should run.
There is no guarantee that which runnable thread will be chosen to run
by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.
Difference between preemptive scheduling and time slicing
Under preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes into
existence.
Under time slicing, a task executes for a predefined slice of time and
then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
10
Java Thread Methods
1) void start() - It is used to start the execution of the thread.
2) void run() - It is used to do an action for a thread.
3) static void sleep() - It blocks a thread for the specified amount of time.
4) static Thread currentThread() -It returns a reference to the currently
executing thread object.
5) void join() - It will put the current thread on wait until the thread on
which it is called is dead. If thread is interrupted then it will throw
InterruptedException.
6) int getPriority() - It returns the priority of the thread.
7) void setPriority() - It changes the priority of the thread.
8) String getName() - It returns the name of the thread.
9) void setName() - It changes the name of the thread.
10) long getId() - It returns the id of the thread.
11
Java Thread Methods
11) boolean isAlive() - It tests if the thread is alive.
12) static void yield() - It causes the currently executing thread
object to pause and allow other threads to execute temporarily.
13) void suspend() - It is used to suspend the thread.
14) void resume() - It is used to resume the suspended thread.
15) void stop() - It is used to stop the thread.
16) void wait() - Thread waits until othe bject is notified.
17) void notify() - It is used to give the notification for only
one thread which is waiting for a particular object.
18) void notifyAll() - It is used to give the notification to all
waiting threads of a particular object.

12
Thread Priority
Each thread has a priority. Priorities are represented by a number
between 1 and 10. In most cases, thread schedular schedules the
threads according to their priority. But it is not guaranteed
because it depends on JVM specification that which scheduling it
chooses.
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value
of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is
10.

13
Synchronization
When two or more threads need access to a shared resource, they
need some way to ensure that the resource will be used by only
one thread at a time. The process by which this is achieved is
called synchronization.
The synchronization is mainly used:
1)To prevent thread interference.
2)To prevent inconsistency problem.
Key to synchronization is the concept of the monitor (also called
a semaphore). A monitor is an object that is used as a mutually
exclusive lock, or mutex.
Only one thread can own a monitor at a given time. When a
thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other
threads are said to be waiting for the monitor. 14
Synchronization
Synchronization can be achieved by
1) synchronized method
2) synchronized block
3) static synchronization (on static methods)
If you declare any method as synchronized, it is known as
synchronized method.
Synchronized method is used to lock an object for any shared
resource.
When a thread invokes a synchronized method, it automatically
acquires the lock for that object and releases it when the thread
completes its task.
(Refer Lab experimt-7 for synchrization method)
15
Synchronization
Synchronized block can be used to perform synchronization on
any specific resource of the method.
Suppose we have 50 lines of code in our method, but we want to
synchronize only 5 lines, we can use synchronized block.
If we put all the code of the method in the synchronized block, it
will work same as the synchronized method.
Synchronized block is used to lock an object for any shared
resource.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object_reference)
{
//code block
} 16
Synchronization

Problem without static


Synchronization:
Suppose there are two objects of a shared class(MulTable) named
object1 and object2.In case of synchronized method and synchronized
block there cannot be interference between t1 and t2 or t3 and t4 because
t1 and t2 both refers to a common object that have a single lock.But
there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock. If we want no
interference between t1 and t3 or t2 and t4, static synchronization solves
this problem. 17
Deadlock in Threads
Deadlock can occur in a situation when a thread is waiting for an
object lock, that is acquired by another thread and second thread
is waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock,
the condition is called deadlock.

18
Inter-Thread Communication
Inter-thread communication (Co-operation) is all about allowing
synchronized threads to communicate with each other.
It is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in
the same critical section to be executed.
It is implemented by following methods of Object class:
◆ wait()
◆ notify()
◆ notifyAll()
These methods are implemented as final methods in Object class,
so all classes have them. All three methods can be called only
from within a synchronized context.
19
Inter-Thread Communication
wait( ) tells the calling thread to give up the objet's monitor and
go to blocked state 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( )

20
Java Data Base
Connectivity
Introduction
JDBC stands for Java Database Connectivity. JDBC is a Java
API to connect and execute the query with the database. It is a
part of JavaSE (Java Standard Edition).
JDBC is a specification from Sun microsystems that provides a
standard API for java applications to communicate with various
databases.
It is used to write programs required to access databases. JDBC
along with the database driver is capable of accessing data bases.
The enterprise data stored in a relational database can be
accessed with the help of JDBC APIs.
The classes and interfaces of JDBC allows application to send
request made by users to the specified database.

22
JDBC Architecture
JDBC Components:

23
JDBC Architecture
The java.sql package contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:
● Driver interface
● Connection interface
● Statement interface
● PreparedStatement interface
● CallableStatement interface
● ResultSet interface
A list of popular classes of JDBC API are given below:
● DriverManager class
● Blob class
● Clob class
● Types class
24
JDBC Drivers
JDBC API uses JDBC drivers to connect with the database.
JDBC Driver is a software component that enables java application to
interact with the database.
There are 4 types of JDBC drivers:
● JDBC-ODBC Bridge Driver
● Native-API Driver (partially java driver)
● Network Protocol Driver (fully java driver)
● Thin Driver (fully java driver)
We can use JDBC API to access tabular data stored in any relational
database. By the help of JDBC API, we can save, update, delete and
fetch data from the database.
API (Application programming interface) is a code that enables two
software applications communicate. It represents classes and
interfaces that software programs can follow to communicate with
each other. 25
JDBC-ODBC Bridge Driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to
the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls.

26
JDBC-ODBC Bridge Driver
Oracle does not support the JDBC-ODBC Bridge from Java 8.
Oracle recommends that you use JDBC drivers provided by the
vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
◆ Easy to use.
◆ Can be easily connected to any database.
Disadvantages:
◆ Performance degraded because JDBC method call is
converted into the ODBC function calls.
◆ The ODBC driver needs to be installed on the client
machine.

27
Native-API Driver
The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into native
calls of the database API. It is not written entirely in java.

28
Native-API Driver
Advantage:
◆ Performance upgraded than JDBC-ODBC bridge
driver.
Disadvantages:
◆ The Native driver needs to be installed on the each
client machine.
◆ The Vendor client library needs to be installed on client
machine.

29
Network Protocol Driver
The Network Protocol driver uses middleware (application
server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is fully written in java.

30
Network Protocol Driver
Advantage:
◆ No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
Disadvantages:
◆ Network support is required on client machine.
◆ Requires database-specific coding to be done in the
middle tier.
◆ Maintenance of Network Protocol driver becomes
costly because it requires database-specific coding to be
done in the middle tier.

31
Thin driver
The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known as
thin driver. It is fully written in Java language.

32
Thin driver
Advantages:
◆ Better performance than all other drivers.
◆ No software is required at client side or server side.
Disadvantage:
◆ Drivers depend on the Database.

33
JDBC Steps
There are 5 steps to connect any java application with the database
using JDBC. These steps are as follows:

Register the Driver class:


The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
Create connection:
The getConnection() method of DriverManager class is used to
establish connection with the database.
Create statement:
The createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries
with the database.
34
JDBC Steps
Execute queries:
The executeQuery() method of Statement interface is used to
execute queries to the database. This method returns the object of
ResultSet that can be used to get all the records of a table.
Close connection:
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used
to close the connection.

35
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps
track of the drivers that are available and handles establishing a connection
between a database and the appropriate driver.
The DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
Useful methods of DriverManager class
1) public static void registerDriver(Driver driver): It is used to register the given
driver with DriverManager.
2) public static void deregisterDriver(Driver driver): It is used to deregister the
given driver (drop the driver from the list) with DriverManager.
3) public static Connection getConnection(String url): It is used to establish the
connection with the specified url.
4) public static Connection getConnection(String url,String userName,String
password): It is used to establish the connection with the specified url,
username and password.
36
Connection interface
A Connection is the session between java application and
database.The object of Connection can be used to get the object of
Statement, PreparedStatement, and DatabaseMetaData.
The Connection interface provide many methods for transaction
management like commit(), rollback() etc.

Commonly used methods of Connection interface:


1) public Statement createStatement(): Creates a statement object that
can be used to execute SQL queries.
2) public Statement createStatement(int resultSetType,int
resultSetConcurrency): Creates a Statement object that will generate
ResultSet objects with the given type and concurrency.

37
Connection interface
3) public void setAutoCommit(boolean status): Used to set the commit
status.By default it is true.
4) public void commit(): Saves the changes made since the previous
commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous
commit/rollback.
6) public void close(): Closes the connection and Releases a JDBC
resources immediately.

38
Statement interface
The Statement interface provides methods to execute queries
with the database.
The statement interface is a factory of ResultSet i.e. it provides
factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
1) public ResultSet executeQuery(String sql): Used to execute
SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): Used to execute specified
query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): Used to execute queries that
may return multiple results.
4) public int[] executeBatch(): Used to execute batch of commands.
39
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a
table. Initially, cursor points to before the first row.
By default, ResultSet object can be moved forward only and it is
not updatable.
But we can make this object to move forward and backward
direction by passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

40
ResultSet interface
Commonly used methods of ResultSet interface:
1) public boolean next(): is used to move the cursor to the one row
next from the current position.
2) public boolean previous(): is used to move the cursor to the one
row previous from the current position.
3) public boolean first(): is used to move the cursor to the first row
in result set object.
4) public boolean last(): is used to move the cursor to the last row
in result set object.
5) public boolean absolute(int row): is used to move the cursor to
the specified row number in the ResultSet object.

41
ResultSet interface
6) public boolean relative(int row): is used to move the cursor to
the relative row number in the ResultSet object, it may be
positive or negative.
7) public int getInt(int columnIndex): is used to return the data
of specified column index of the current row as int.
8) public int getInt(String columnName): is used to return the
data of specified column name of the current row as int.
9) public String getString(int columnIndex): is used to return the
data of specified column index of the current row as String.
10) public String getString(String columnName): is used to return
the data of specified column name of the current row as String.

42
PreparedStatement interface
The PreparedStatement interface is a sub interface of Statement.
It is used to execute parameterized query. For eg:
String sql="insert into emp values(?,?,?)";
We are passing parameter (?) for the values. Its value will be set
by calling the setter methods of PreparedStatement.
The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only
once.
The prepareStatement() method of Connection interface is used
to return the object of PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query) throws
SQLException{}
43
PreparedStatement interface
The important methods of PreparedStatement interface are given below:
✔ public void setInt(int paramIndex, int value) sets the integer value to
the given parameter index.
✔ public void setString(int paramIndex, String value) sets the String value
to the given parameter index.
✔ public void setFloat(int paramIndex, float value) sets the float value to
the given parameter index.
✔ public void setDouble(int paramIndex, double value) sets the double
value to the given parameter index.
✔ public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
✔ public ResultSet executeQuery() executes the select query. It returns
an instance of ResultSet.
44

You might also like