Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package csci3030u.a3;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import com.mysql.jdbc.Connection;
- import com.mysql.jdbc.Statement;
- /*
- * Creates 2 connections to database and by using 2 threads, accesses the database at the same time.
- * One thread will be inserting values and deleting them, the other thread will query the database
- */
- public class ConcurrentAccess {
- public static void main(String[] args) {
- String host=null, user=null, password=null, database=null;
- int trials=0;
- //collect arguments and store them in variables
- if(args.length !=5){
- System.out.println("Not enough args");
- System.exit(0);
- }else{
- host=args[0];
- user=args[1];
- password=args[2];
- database=args[3];
- trials = Integer.parseInt(args[4]);
- }
- //connect to database twice
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch(Exception e) {
- System.out.println("Driver not loaded."); System.exit(0);
- }
- try {
- //initialze connection 1 and 2
- Connection con1 = (Connection) DriverManager.getConnection(
- host+database, user, password);
- Connection con2 = (Connection) DriverManager.getConnection(
- host+database, user, password);
- //create table if not exists
- Statement stmt = (Statement) con1.createStatement();
- stmt.executeUpdate("CREATE TABLE IF NOT EXISTS A3(number INTEGER)");
- //setup threads that will run connection
- InsertThread t1= new InsertThread(trials,con2);
- QueryThread t2= new QueryThread(trials,con1 );
- //run threads
- t1.run();
- t2.run();
- con1.close();
- con2.close();
- } catch(Exception e) {
- System.out.println(e.getMessage());
- System.out.println("Driver not loaded."); System.exit(0);
- }
- }
- }
- /*
- * Thread used in max min querying
- */
- class QueryThread implements Runnable {
- int trials;
- Connection con;
- int collisions;
- QueryThread(int trials, java.sql.Connection dbCon) {
- this.trials=trials;
- this.con=(Connection) dbCon;
- this.collisions=0;
- }
- /**
- * Separate thread for database Queries
- */
- public void run() {
- try {
- con.setAutoCommit(true);
- for(int i=0; i<trials; i++){
- if(AccessTable.queryMaxMin(con)){
- collisions++;
- }
- }
- System.out.println("Number of collisions: " + collisions);
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- return;
- }
- }
- }
- /*
- * Thread used in value inserting
- */
- class InsertThread implements Runnable {
- int trials;
- Connection con;
- InsertThread(int trials, java.sql.Connection dbCon) {
- this.con=(Connection) dbCon;
- }
- /**
- * Separate thread for database Queries
- */
- public void run() {
- try {
- con.setAutoCommit(true);
- for(int i=0; i<trials; i++){
- AccessTable.insertValues(con, 1, 10);
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement