ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Basic Object Pool Implementation

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1import java.util.concurrent.ArrayBlockingQueue;
2import java.util.concurrent.BlockingQueue;
3
4public class StringBuilderPool {
5
6private final BlockingQueue<StringBuilder> pool;
7private final int poolSize;
8
9public StringBuilderPool(int poolSize) {
10this.poolSize = poolSize;
11this.pool = new ArrayBlockingQueue<>(poolSize);
12// Initialize the pool with empty StringBuilders
13for (int i = 0; i < poolSize; i++) {
14try {
15pool.put(new StringBuilder());
16} catch (InterruptedException e) {
17Thread.currentThread().interrupt();
18System.err.println("Failed to initialize pool: " + e.getMessage());
19}
20}
21}
22
23public StringBuilder acquire() throws InterruptedException {
24// Take a StringBuilder from the pool. Blocks if pool is empty.
25StringBuilder sb = pool.take();
26sb.setLength(0); // Reset the StringBuilder for reuse
27return sb;
28}
29
30public void release(StringBuilder sb) throws InterruptedException {
31if (sb != null) {
32sb.setLength(0); // Clear content before returning
33// Return the StringBuilder to the pool. Blocks if pool is full.
34if (pool.size() < poolSize) {
35pool.put(sb);
36} else {
37// Optionally log or handle the case where pool is already full
38System.out.println("Pool is full, discarding StringBuilder.");
39}
40}
41}
42
43public int getPoolSize() {
44return poolSize;
45}
46
47public int getCurrentSize() {
48return pool.size();
49}
50
51public static void main(String[] args) {
52StringBuilderPool pool = new StringBuilderPool(5);
53
54try {
55StringBuilder sb1 = pool.acquire();
56sb1.append("Hello");
57System.out.println("Acquired SB1: " + sb1.toString() + ", Pool size: " + pool.getCurrentSize());
58
59StringBuilder sb2 = pool.acquire();
60sb2.append("World");
61System.out.println("Acquired SB2: " + sb2.toString() + ", Pool size: " + pool.getCurrentSize());
62
63pool.release(sb1);
64System.out.println("Released SB1. Pool size: " + pool.getCurrentSize());
65
66StringBuilder sb3 = pool.acquire();
67sb3.append("Java");
68System.out.println("Acquired SB3: " + sb3.toString() + ", Pool size: " + pool.getCurrentSize());
69
70pool.release(sb2);
71pool.release(sb3);
72System.out.println("Released SB2 and SB3. Pool size: " + pool.getCurrentSize());
73
74// Example of pool full scenario (if poolSize is small)
75for (int i = 0; i < pool.getPoolSize(); i++) {
76pool.acquire();
77}
78System.out.println("Acquired all objects. Pool size: " + pool.getCurrentSize());
79StringBuilder sb4 = pool.acquire(); // This will block or discard if not handled
80pool.release(sb4);
81
82} catch (InterruptedException e) {
83Thread.currentThread().interrupt();
84System.err.println("Operation interrupted: " + e.getMessage());
85}
86}
87}
Algorithm description viewbox

Basic Object Pool Implementation

Algorithm description:

This `StringBuilderPool` class manages a collection of reusable `StringBuilder` objects. Instead of creating new `StringBuilder` instances repeatedly, which can be inefficient, this pool allows threads to `acquire` an existing `StringBuilder` and `release` it back when done. This reduces object creation overhead and can improve performance, especially in high-throughput applications. The pool uses a `BlockingQueue` to ensure thread-safe access and to handle cases where the pool might be empty or full.

Algorithm explanation:

The `StringBuilderPool` uses an `ArrayBlockingQueue` to store available `StringBuilder` objects. The constructor initializes the pool with a specified number of `StringBuilder` instances. The `acquire` method uses `pool.take()`, which blocks if the queue is empty until an object is available. It then resets the `StringBuilder`'s length to 0 before returning it. The `release` method takes a `StringBuilder`, resets its length, and attempts to add it back to the pool using `pool.put()`, which blocks if the pool is full. If the pool is already at capacity, the released `StringBuilder` is discarded. The time complexity for `acquire` and `release` is O(1) on average, assuming no blocking. Space complexity is O(poolSize) to store the objects in the pool. This design ensures efficient reuse of objects and thread-safe operations.

Pseudocode:

Class StringBuilderPool:
  BlockingQueue pool
  int poolSize

  constructor(poolSize):
    initialize pool with poolSize empty StringBuilders

  method acquire():
    take StringBuilder from pool (block if empty)
    reset StringBuilder length to 0
    return StringBuilder

  method release(sb):
    if sb is not null:
      reset StringBuilder length to 0
      if pool is not full:
        put StringBuilder back into pool (block if full)
      else:
        discard StringBuilder

  main method:
    create pool
    acquire and use StringBuilders
    release StringBuilders
    demonstrate pool full scenario