-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectPool.js
More file actions
69 lines (54 loc) · 1.73 KB
/
ObjectPool.js
File metadata and controls
69 lines (54 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Build a database connection pool manager where clients can acquire and release connections efficiently.
class DBConnection {
constructor(id) {
this.id = id;
this.inUse = false;
}
query(sql) {
console.log(`🔌 [Connection ${this.id}] Running query: ${sql}`);
}
}
class DBConnectionPoolManager {
static #instance = null // private static instance -- all class will have same instance
// singleton pattern this static private
#pool = []
#INITIAL_POOL_SIZE = 3;
constructor() {
if (DBConnectionPoolManager.#instance) {
throw new Error("Use getInstance() instead of new!");
}
for (let i = 1; i <= this.#INITIAL_POOL_SIZE; i++) {
this.#pool.push(new DBConnection(i));
}
}
static getInstance() {
if(!DBConnectionPoolManager.#instance) {
DBConnectionPoolManager.#instance = new DBConnectionPoolManager()
}
return DBConnectionPoolManager.#instance;
}
acquire() {
const conn = this.#pool.find(c => !c.inUse);
if(conn) {
conn.inUse = true;
console.log("Connection Locked");
return conn;
}
return null;
}
release(conn) {
conn.inUse = true;
console.log("Connection Released");
}
}
const pool = DBConnectionPoolManager.getInstance();
const conn1 = pool.acquire();
conn1?.query("SELECT * FROM users");
const conn2 = pool.acquire();
conn2?.query("SELECT * FROM products");
const conn3 = pool.acquire();
conn3?.query("SELECT * FROM orders");
const conn4 = pool.acquire(); // ❌ No available connections
pool.release(conn1);
const conn5 = pool.acquire(); // ✅ Reuses conn1
conn5?.query("SELECT * FROM sales");