Skip to content

Commit 3c4912a

Browse files
Add files via upload
1 parent 7c37a7d commit 3c4912a

File tree

7 files changed

+365
-0
lines changed

7 files changed

+365
-0
lines changed

Code/company/Account.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.concurrentprogramming.company;
2+
3+
4+
import java.sql.Connection;
5+
import java.sql.PreparedStatement;
6+
import java.sql.ResultSet;
7+
import java.sql.SQLException;
8+
import java.util.concurrent.locks.ReentrantLock;
9+
10+
import com.concurrentprogramming.dataaccesslayer.DataAccess;
11+
import com.concurrentprogramming.dataaccesslayer.Services;
12+
13+
public class Account {
14+
15+
public double account_balance;
16+
public int account_id;
17+
18+
public Account(int num, double bal) {
19+
this.account_id = num;
20+
this.account_balance = bal;
21+
}
22+
23+
// This function deposits amount to account
24+
public synchronized boolean deposit(Account acc, double amount) {
25+
Services service = new Services(); //DB services
26+
double new_balance = -1.0; //to check for success status in DB transactions
27+
28+
acc.account_balance = service.getBalanceForAccId(acc.account_id); //fetches balance from DB
29+
acc.account_balance = acc.account_balance + amount; //increments the balance by amount that is to be deposited
30+
new_balance = service.setBalanceForAccId(acc.account_id, acc.account_balance); //sets the updated balance to DB
31+
System.out.println("New balance in Account ID " + acc.account_id + " is € " + new_balance);
32+
if (new_balance == -1.0) {
33+
return false; //DB update was unsuccessful
34+
} else {
35+
return true; //DB update was successful
36+
}
37+
}
38+
39+
// This function withdraws amount from account
40+
public synchronized boolean withdraw(Account acc, double amount) {
41+
Services service = new Services(); //DB services
42+
double new_balance = -1.0; //to check for success status in DB transactions
43+
44+
acc.account_balance = service.getBalanceForAccId(acc.account_id); //fetches balance from DB
45+
if (amount <= acc.account_balance) { //checks if account has enough balance to be withdrawn
46+
acc.account_balance = acc.account_balance - amount; //decrements the balance by amount that is to be withdrawn
47+
new_balance = service.setBalanceForAccId(acc.account_id, acc.account_balance); //sets the updated balance to DB
48+
System.out.println("New balance in Account ID " + acc.account_id + " is € " + new_balance);
49+
} else {
50+
System.out.println("Insufficient funds in Account ID " + acc.account_id + ". Withdrawal was unsuccessful.");
51+
}
52+
if (new_balance == -1.0) {
53+
return false; //DB update was unsuccessful
54+
} else {
55+
return true; //DB update was successful
56+
}
57+
}
58+
59+
// This function transfers amount from source account to destination account
60+
public synchronized void transferFunds(Account acc, Account destinationAcc, double amount) {
61+
if (withdraw(acc, amount)) { //if withdrawal is successful from source account then deposit amount to destination account
62+
if (!deposit(destinationAcc, amount)) { //if deposit is unsuccessful to destination account then deposit back amount to source account
63+
System.out.println("Transfer of amount "+ amount +" from source Account ID " + acc.account_id + " to destination Account ID " + destinationAcc.account_id + " was unsuccessful.");
64+
deposit(acc, amount);
65+
}
66+
}
67+
}
68+
69+
}

Code/company/AccountList.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.concurrentprogramming.company;
2+
3+
import java.util.ArrayList;
4+
import com.concurrentprogramming.company.Account;
5+
import com.concurrentprogramming.dataaccesslayer.Services;
6+
7+
public class AccountList {
8+
9+
public static ArrayList<Account> accountList;
10+
11+
// Creates an ArrayList of Account type
12+
public ArrayList<Account> createAccountArrayList() {
13+
accountList = new ArrayList<Account>();
14+
Services service = new Services();
15+
double bal;
16+
// it initializes the 50 accounts with Account ID from 1 to 50
17+
// and balance as fetched from DB for the IDs 1 to 50 respectively
18+
for (int i = 0; i < 51; i++) {
19+
bal = service.getBalanceForAccId(i);
20+
accountList.add(new Account(i, bal));
21+
}
22+
return accountList;
23+
}
24+
}

Code/company/Department.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.concurrentprogramming.company;
2+
3+
import java.util.ArrayList;
4+
5+
public class Department implements Runnable {
6+
7+
private int dept_id;
8+
private int acc_id;
9+
private int tr_id;
10+
private int amt;
11+
private int acc_id_second;
12+
public static ArrayList<Account> accountList;
13+
14+
// Department constructor overloaded for TransferAccount (trID=2) scenario
15+
public Department(int deptId, int trId, int amount, int accId, int accIdSecond, ArrayList<Account> list) {
16+
dept_id = deptId;
17+
tr_id = trId;
18+
amt = amount;
19+
acc_id = accId;
20+
acc_id_second = accIdSecond;
21+
accountList = list;
22+
}
23+
24+
// Department constructor overloaded for Deposit and Withdrawal (trID=0 and
25+
// TrID=1) scenario
26+
public Department(int deptId, int trId, int amount, int accId, ArrayList<Account> list) {
27+
dept_id = deptId;
28+
tr_id = trId;
29+
amt = amount;
30+
acc_id = accId;
31+
accountList = list;
32+
}
33+
34+
// Defining runnable tasks for each Thread
35+
// Based of TrID being 0,1,2 -> respective calls are made to Deposit, Withdraw
36+
// and TransferFunds
37+
@Override
38+
public void run() {
39+
Account account = accountList.get(this.acc_id);
40+
switch (this.tr_id) {// 0 = deposit; 1 = withdraw; 2 = transferFunds;
41+
case 0: //Deposit
42+
System.out.println(Thread.currentThread().getName() + " is helping Department ID " + this.dept_id + " in making a deposit of € " + this.amt + " to Account ID "
43+
+ this.acc_id);
44+
account.deposit(account, this.amt);
45+
break;
46+
case 1: //Withdraw
47+
System.out.println(Thread.currentThread().getName() + " is helping Department ID " + this.dept_id + " in making a withdrawal of € " + this.amt
48+
+ " from Account ID " + this.acc_id);
49+
account.withdraw(account, this.amt);
50+
break;
51+
case 2: //TransferFunds
52+
System.out.println(Thread.currentThread().getName() + " is helping Department ID " + this.dept_id + " in making a transfer of € " + this.amt
53+
+ " from Account ID " + this.acc_id + " to Account ID " + this.acc_id_second);
54+
Account destinationAccount = accountList.get(this.acc_id_second);
55+
account.transferFunds(account, destinationAccount, this.amt);
56+
break;
57+
}
58+
}
59+
}

Code/dataaccesslayer/DataAccess.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.concurrentprogramming.dataaccesslayer;
2+
3+
import java.sql.Connection;
4+
import java.sql.DriverManager;
5+
6+
public class DataAccess {
7+
8+
static Connection dbConnection;
9+
//Creates a DB connection and returns to the calling function
10+
public synchronized static Connection getDbAccess() {
11+
try {
12+
13+
Class.forName("com.mysql.jdbc.Driver");
14+
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/CP_Schema?useSSL=false", "root", "sql12345");
15+
if (dbConnection != null) {
16+
//System.out.println("Connected to SQL Database and Schema");
17+
}
18+
19+
} catch (Exception e) {
20+
e.printStackTrace();
21+
}
22+
return dbConnection;
23+
}
24+
}

Code/dataaccesslayer/Services.java

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package com.concurrentprogramming.dataaccesslayer;
2+
3+
import java.sql.Connection;
4+
import java.sql.PreparedStatement;
5+
import java.sql.ResultSet;
6+
import java.sql.SQLException;
7+
import java.sql.Statement;
8+
import java.util.ArrayList;
9+
10+
public class Services {
11+
12+
ArrayList<Integer> deptIds = new ArrayList<Integer>();
13+
ArrayList<Integer> accountIds = new ArrayList<Integer>();
14+
15+
// Fetches all the Department IDs from DB
16+
public ArrayList getAllDepartmentIds() {
17+
Connection dbAccess = DataAccess.getDbAccess();
18+
Statement sttmnt;
19+
ResultSet rs;
20+
try {
21+
sttmnt = dbAccess.createStatement();
22+
rs = sttmnt.executeQuery("SELECT dept_id FROM departments");
23+
while (rs.next()) {
24+
deptIds.add(rs.getInt("dept_id"));
25+
}
26+
dbAccess.close();
27+
} catch (SQLException se) {
28+
se.printStackTrace();
29+
} catch (Exception e) {
30+
e.printStackTrace();
31+
}
32+
return deptIds;
33+
}
34+
35+
// Fetches all the Account IDs from DB
36+
public ArrayList getAllAccountIds() {
37+
Connection dbAccess = DataAccess.getDbAccess();
38+
Statement sttmnt;
39+
ResultSet rs;
40+
try {
41+
sttmnt = dbAccess.createStatement();
42+
rs = sttmnt.executeQuery("SELECT acc_id FROM accounts");
43+
while (rs.next()) {
44+
accountIds.add(rs.getInt("acc_id"));
45+
}
46+
dbAccess.close();
47+
} catch (SQLException se) {
48+
se.printStackTrace();
49+
} catch (Exception e) {
50+
e.printStackTrace();
51+
}
52+
return accountIds;
53+
}
54+
55+
// Fetches balance of a particular ID from DB
56+
public synchronized double getBalanceForAccId(int AccId) {
57+
Connection dbAccess = DataAccess.getDbAccess();
58+
PreparedStatement psttmnt;
59+
ResultSet rs;
60+
String querySting;
61+
double balance = -1.0;
62+
try {
63+
querySting = "SELECT acc_balance FROM accounts where acc_id = " + AccId;
64+
psttmnt = dbAccess.prepareStatement(querySting);
65+
rs = psttmnt.executeQuery();
66+
while (rs.next()) {
67+
balance = rs.getDouble("acc_balance");
68+
}
69+
dbAccess.close();
70+
} catch (SQLException se) {
71+
se.printStackTrace();
72+
} catch (Exception e) {
73+
e.printStackTrace();
74+
}
75+
return balance;
76+
}
77+
78+
// Sets/Updates balance for a particular ID in DB
79+
public synchronized double setBalanceForAccId(int AccId, double bal) {
80+
Connection dbAccess = DataAccess.getDbAccess();
81+
PreparedStatement psttmnt;
82+
String querySting;
83+
double balance = -1.0;
84+
try {
85+
querySting = "UPDATE accounts SET acc_balance = " + bal + " WHERE acc_id = " + AccId;
86+
psttmnt = dbAccess.prepareStatement(querySting);
87+
int result = psttmnt.executeUpdate();
88+
if (result != 0) {
89+
balance = getBalanceForAccId(AccId);
90+
}
91+
dbAccess.close();
92+
} catch (SQLException se) {
93+
se.printStackTrace();
94+
} catch (Exception e) {
95+
e.printStackTrace();
96+
}
97+
return balance;
98+
}
99+
}

Code/main/Main.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.concurrentprogramming.main;
2+
3+
import java.util.ArrayList;
4+
import java.util.concurrent.ExecutorService;
5+
import java.util.concurrent.Executors;
6+
7+
import com.concurrentprogramming.company.Account;
8+
import com.concurrentprogramming.company.AccountList;
9+
import com.concurrentprogramming.company.Department;
10+
import com.concurrentprogramming.randomgenerator.RandomGenerator;
11+
12+
13+
public class Main {
14+
15+
public static ArrayList<Account> accountsList = new AccountList().createAccountArrayList();
16+
17+
public static void main(String[] args) {
18+
19+
int rDeptId = 0, rAccId = 0, rTrId = 0, rAmt = 0, rAccIdSecond = 0;
20+
21+
int numberOfCores = Runtime.getRuntime().availableProcessors();
22+
ExecutorService executor = Executors.newFixedThreadPool(numberOfCores); //number of threads are the same as number of cores available on system (for better performance). Here, it is 4
23+
24+
RandomGenerator ranGen = new RandomGenerator();
25+
for(int i=0;i<15000;i++) {
26+
Runnable dept;
27+
rAccIdSecond = 0; //initialize destination Account ID to 0 at start of every loop
28+
rDeptId = ranGen.getRandomDeptId(); //generate a random Department ID
29+
rAccId = ranGen.getRandomAccId(); //generate a random Account ID
30+
rTrId = ranGen.getRandomTransactionId(); //generate a random Transaction ID to choose from deposit, withdrawal and transfer funds
31+
rAmt = ranGen.getRandomAmount(); //generate a random amount to transact with
32+
if(rTrId==2) { // 2 => TransferFunds
33+
rAccIdSecond = ranGen.getRandomAccId(); //generate a random destination account ID
34+
while(rAccIdSecond == rAccId) {
35+
rAccIdSecond = ranGen.getRandomAccId(); //generate a destination account ID until it differs from source account ID
36+
}
37+
dept = new Department(rDeptId,rTrId,rAmt,rAccId,rAccIdSecond,accountsList); //call overloaded constructor of department class
38+
}else {
39+
dept = new Department(rDeptId,rTrId,rAmt,rAccId,accountsList); //call overloaded constructor of department class
40+
}
41+
executor.execute(dept);
42+
}
43+
executor.shutdown();
44+
while(!executor.isTerminated()) {};
45+
System.out.println("Threads have finished executing their tasks.");
46+
}
47+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.concurrentprogramming.randomgenerator;
2+
3+
import java.util.ArrayList;
4+
import java.util.Random;
5+
6+
import com.concurrentprogramming.dataaccesslayer.Services;
7+
8+
public class RandomGenerator {
9+
10+
Random random = new Random();
11+
Services service = new Services();
12+
int[] trIds = { 0, 1, 2 };
13+
int randomTrId;
14+
int randomAmount;
15+
int randomDeptId;
16+
int randomAccId;
17+
18+
// Generates a random Department ID from the list of Department IDs
19+
public int getRandomDeptId() {
20+
ArrayList<Integer> deptIds = service.getAllDepartmentIds();
21+
randomDeptId = deptIds.get(random.nextInt(deptIds.size()));
22+
return randomDeptId;
23+
}
24+
25+
// Generates a random Account ID from the list of Account IDs
26+
public int getRandomAccId() {
27+
ArrayList<Integer> accIds = service.getAllAccountIds();
28+
randomAccId = accIds.get(random.nextInt(accIds.size()));
29+
return randomAccId;
30+
}
31+
32+
// Generates a random Transaction ID from the list of Transaction IDs
33+
public int getRandomTransactionId() {
34+
randomTrId = trIds[random.nextInt(trIds.length)];
35+
return randomTrId;
36+
}
37+
38+
// Generates a random Amount between 500 and 100
39+
public int getRandomAmount() {
40+
randomAmount = random.nextInt((500 - 100) + 1) + 100; // random number between 500 and 100
41+
return randomAmount;
42+
}
43+
}

0 commit comments

Comments
 (0)