Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- we know the servlet instance is created once and based on multiple user requests to the servlet , container creates threads to address each of the user request.
- public class Demo {
- public static void main(String[] args) {
- DBThread db = new DBThread();
- //Only one instance and multiple threads
- Thread request1= new Thread(db, "request1");
- Thread request2= new Thread(db, "request2");
- request1.start();
- request2.start();
- }
- }
- DBThread.java
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class DBThread implements Runnable {
- public void getData(){
- Connection con=null;
- Statement statement = null;
- CallableStatement callProcedure = null;
- ResultSet rs = null;
- try {
- con = getDBConnection();
- if(con==null)
- System.out.println("Unable to get connection for " + Thread.currentThread().getName());
- else
- {
- callProcedure = con.prepareCall("{call PROCEDURE1(?)}");
- callProcedure.setString(1,Thread.currentThread().getName());
- callProcedure.execute();
- statement = con.createStatement();
- rs = statement.executeQuery("select id,inputname from temp1");
- while(rs.next()){
- System.out.println("Thread "+Thread.currentThread().getName() +":"+ rs.getString(1) +":" + rs.getString(2));
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally{
- try{
- if(callProcedure!=null){
- callProcedure.close();
- }
- if(rs!=null)
- rs.close();
- if(con!=null){
- con.close();
- System.out.println("Connection close for " + Thread.currentThread().getName());
- }
- }catch(Exception e){
- System.out.println("print therea" + Thread.currentThread().getName());
- }
- }
- }
- public void run() {
- this.getData();
- }
- public Connection getDBConnection() throws SQLException, Exception{
- String user = null;
- String pwd = null;
- String dbURL = null;
- String driverClassName = null;
- Connection con = null;
- if(con == null || con.isClosed() == true){
- user = "readonly";
- pwd = "XXXX"
- dbURL = "jdbc:oracle:thin:@host:port:SID;
- driverClassName = "oracle.jdbc.driver.OracleDriver";
- Class.forName(driverClassName);
- con = DriverManager.getConnection(dbURL, user, pwd);
- }
- System.out.println("Connection got for " + Thread.currentThread().getName()+ "Connection "+ con);
- return con;
- }
- }
- Oracle procedure :
- create or replace
- PROCEDURE PROCEDURE1(id varchar2) AS
- BEGIN
- DELETE from temp1;
- FOR i IN 1..5 LOOP
- INSERT INTO temp1 VALUES (i,id);
- END LOOP;
- COMMIT;
- END PROCEDURE1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement