Professional Documents
Culture Documents
Core Java - JDBC - Muralidhar 1
Core Java - JDBC - Muralidhar 1
Threads
JDBC
Threads
Improved performance
Minimized system resource usage
Simultaneous access to multiple applications
Program structure simplification
Send & receive data on network
Read & write files to disk
Perform useful computation (editor, browser, game)
Process V S Thread
Definition
Address Space
2. Has own address space – variables & 2. Shares address space with other
data structures (in memory) threads.
Process V S Thread
Single Thread
Two Threads
1. Process-based multitasking
2. Thread-based multitasking
1. Process-based multitasking
2. Thread-based multitasking
Race condition
Deadlock condition
Lock starvation
How To
Use
Threads in
Java
Using Thread
class
Thread Class
Declaration
Thread Class
Methods
Thread Class
Methods
Runnable By calling the start() method that in turn call run() method.
th.start();
sleep() stop()
Sleeping Running Terminated
timeout return
State Diagram
new start
notify, notifyAll,
new runnable
IO complete,
sleep expired,
scheduler yield, join complete
time slice
running blocked
IO, sleep,
terminate wait, join
dead
• The class extending the Thread class calls start() method to begin
executing child thread.
Sample
Code
public class MyT extends Thread {
public void run() {
…
}
}
MyT T = new MyT () ; // create thread
T.start(); // begin running thread
…
run() method
public class TestMyThread
is called.
{ The New
public static void main(String[] args) Thread
moves to
{
runnable
MyThread mth1 = new MyThread(“IBM", “Hello"); state or to
mth1.start(); the running
state
} depending
} upon the
scheduler.
36 Core Java | JDBC | Muralidhar
Creating threads (continued)
A newly
public class TestMyRunnable created
{ thread is
moved either
public static void main(String[] args) to runnable
{ or running
state by the
MyRunnable myrun = new MyRunnable(“IBM", “Hello"); scheduler
Thread mythread = new Thread(myrun);
mythread.start();
}
}
51 Core Java | JDBC | Muralidhar
Creating threads (continued)
Possible
Outputs
Point To Be Noted
Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
Each Java thread is given a numeric priority between MIN_PRIORITY and
MAX_PRIORITY.
The Java Run-time system selects the runnable thread with the highest
priority of execution when a number of threads get ready to execute.
The Java Run-time Environment executes threads based on their priority.
A thread with higher priority runs before threads with low priority.
A given thread may, at any time, give up its right to execute by calling the
yield method. Threads can only yield the CPU to other threads of the
same priority--attempts to yield to a lower priority thread are ignored.
• You can set the thread priority after it is created using the setPriority() method declared in the Thread class.
Syntax for
setPriority
method
Why Synchronization?
Problem:
Race condition!
Two or more threads access to same object and each call a method that modifies the
state of the object.
Result:
Corrupted
object
Synchronization
Unsynchronized Synchronized
Thread 1 Thread 2 Thread 1 Thread 2
Time
Transfer
Transfer Transfer
Transfer
What is Synchronization?
What is a Monitor?
A monitor is an object that can block threads and notify them when it is available.
• The monitor controls the way in which synchronized methods access an object or class.
• To enter an object’s monitor, you need to call a synchronized method.
Using
synchronized keyword
Object Locks
63 Core Java | JDBC | Muralidhar
Thread synchronization (continued)
1. Method Level
2. Object Level
1. Synchronizing A Method
1. Synchronizing A Method
2. Synchronizing An Object
public void updateRecord()
{
synchronized (this)
{
// critical code goes here …
}
}
2. Synchronizing An Object
public void updateRecord()
{
synchronized (this)
{
// critical code goes here …
}
}
A thread may notify another thread that the task has been completed. This
communication between threads is known as interthread communication.
Garbage collection is the feature of Java that helps to automatically destroy the
objects created and release their memory for future reallocation.
Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
You can set the thread priority after it is created using the setPriority()
method declared in the Thread class.
Synchronization of threads ensures that if two or more threads need to
access a shared resource, the resource is used by only one thread at a
time.
Various threads can communicate with each other using the following
methods:
– wait()
– notify()
– notifyAll()
Garbage collection is the feature of Java that helps to automatically
destroy the objects created and release their memory for future
reallocation.
74 Core Java | JDBC | Muralidhar
Summary (continued)
http://www.devarticles.com/c/a/Java/Multithreading-in-Java
http://java.sun.com/docs/books/tutorial
http://java.sun.com/j2se/1.3/docs/api/java/lang/Runnable.html
http://telecom.ntua.gr/HTML.Tutorials/applet/overview/threads.html
http://java.sun.com/docs/books/tutorial/essential/threads/
JDBC
Simple.
Client-side scripting offloads work
onto the client.
User Interface
Fat client
Server bottlenecks Client Layer UI Logic
Software Distribution
problem Business Logic
Inflexible
Network
User Data
DML Operations
Validation
Checks
User Interface
Application Server sits between
client and database. Client Layer
UI Logic
Network
Business Messages
Network
User Data
DML
Operations
Validation
Checks
Database Server Database
Layer Tables
higher complexity
higher maintenance
lower network efficiency
more parts to configure (and buy)
Submit Clear
Driver Oracle
Java JDBC
Driver DB2
Application API
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Go Back To
JDBC Driver List
Type I ODBC
JDBC
“Bridge” Driver
Type II
“Native” CLI (.lib)
JDBC
Type III Middleware
“Middleware” Server
Type IV
“Pure”
99 Core Java | JDBC | Muralidhar
Related technoligies
ODBC
– Requires configuration (odbc.ini)
RDO, ADO
– Requires Win32
JavaBlend
– maps objects to tables transparently (more or less)
JDBC API
The JDBC API classes and interfaces are available in the java.sql and the
javax.sql packages.
The commonly used classes and interfaces in the JDBC API are:
– DriverManager class: Loads the driver for a database.
– Driver interface: Represents a database driver. All JDBC driver classes must
implement the Driver interface.
– Connection interface: Enables you to establish a connection between a Java
application and a database.
DriverManager
Driver
Connection
Statement
ResultSet
Load A Driver
Connect to a Database
Load A Driver
Connect to a Database
Example:
Connection
con=DriverManager.getConnection(“jdbc:odbc:MyDSN”,”scott”,”tiger
”);
ResultSet Interface
ResultSet Methods
boolean next()
– activates the next row
– the first call to next() activates the first row
– returns false if there are no more rows
void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it
11. boolean absolute(int rowno) 11. Shifts the cursor to the row number
that you specify as an argument.
ResultSet Fields
ResultSet Fields
SQL Syntax
Database Operations
Querying a table
Inserting rows
Updating rows
Deleting rows
Database Operations
Querying a table
Database Operations
Inserting rows
Database Operations
Updating rows
Database Operations
Deleting rows
DDL Operations
Creating Table
Altering Table
Dropping Table
DDL Operations
Creating Table
DDL Operations
Altering Table
DDL Operations
Dropping Table
PreparedStatement Interface
• The PreparedStatement Interface object:
pass runtime parameters to the SQL statements.
Is compiled and prepared only once by the
JDBC.
prepareStatement() method is used to submit
parameterized query using a connection object to
the database.
CallableStatement Interface
Code snippet for Creating show_emp Stored
Procedure:
CallableStatement Interface
Code snippet for Calling show_emp Stored
Procedure:
Transactions Overview
Transaction = more than one statement which must all succeed (or all
fail) together
If one fails, the system must reverse all previous actions
Also can’t leave DB in inconsistent state halfway through a transaction
COMMIT = complete transaction
ROLLBACK = abort
Transaction Management
Transactions are not explicitly opened and closed
if AutoCommit is true, then every statement is automatically committed
default case: true
if AutoCommit is false, then every statement is added to an ongoing
transaction
Must explicitly rollback or commit.
You can add the driver name to the jdbc.drivers system property to load
and register a JDBC driver manually.
A Connection object establishes a connection between a Java application
and a database.
A Statement object sends requests to and retrieves results from a
database.
You can insert, update, and delete data from a table using the DML
statements in Java applications.
147 Core Java | JDBC | Muralidhar
Summary (continued)
You can create, alter, and drop tables from a database using the DDL
statements in Java applications.
A ResultSet object stores the result retrieved from a database when a
SELECT statement is executed.
You can create various types of ResultSet objects such as read only,
updatable, and forward only.
At the end of Day we see that you are now able to:
Find more information about Threads
Explain and define JDBC