Skip to content

feat: add DoubleBuffer implementation and initial tests #5885

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.thealgorithms.datastructures.buffers;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
* The {@code DoubleBuffer} class implements a double buffering mechanism.
* It maintains two buffers, allowing the program to switch between them.
* This class is useful for separating read/write operations and optimizing memory usage.
*
* @param <Item> The type of elements stored in the double buffer.
*/
public class DoubleBuffer<Item> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about using T instead of Item. Because this is common practice

private final Item[] primaryBuffer;
private final Item[] secondaryBuffer;
private final AtomicInteger primaryIndex;
private final AtomicInteger secondaryIndex;
private final int capacity;
private final AtomicBoolean isPrimaryActive;

/**
* Constructor to initialize the double buffer with a specified capacity.
*
* @param capacity The size of each buffer.
* @throws IllegalArgumentException if the capacity is zero or negative.
*/
public DoubleBuffer(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Buffer size must be positive");
}
// noinspection unchecked
this.primaryBuffer = (Item[]) new Object[capacity];
this.secondaryBuffer = (Item[]) new Object[capacity];
this.primaryIndex = new AtomicInteger(0);
this.secondaryIndex = new AtomicInteger(0);
this.capacity = capacity;
this.isPrimaryActive = new AtomicBoolean(true);
}

/**
* Checks if the active buffer is empty.
*
* @return {@code true} if the active buffer is empty, {@code false} otherwise.
*/
public boolean isEmpty() {
return isPrimaryActive.get() ? primaryIndex.get() == 0 : secondaryIndex.get() == 0;
}

/**
* Switches between the primary and secondary buffers.
*/
public void switchBuffer() {
isPrimaryActive.set(!isPrimaryActive.get());
}

/**
* Checks if the primary buffer is currently active.
*
* @return {@code true} if the primary buffer is active, {@code false} otherwise.
*/
public boolean isPrimaryActive() {
return isPrimaryActive.get();
}

/**
* Adds an item to the active buffer.
*
* @param item The item to be added.
* @throws IllegalArgumentException if the item is null.
*/
public void put(Item item) {
if (item == null) {
throw new IllegalArgumentException("Null items are not allowed");
}

if (isPrimaryActive.get()) {
if (primaryIndex.get() < capacity) {
primaryBuffer[primaryIndex.getAndIncrement()] = item;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you want to make this code thread-safe, will be better to use ReentrantLock for this.

private final ReentrantLock lock = new ReentrantLock();

public void switchBuffer() {
    lock.lock();
    try {
        isPrimaryActive.set(!isPrimaryActive.get());
    } finally {
        lock.unlock();
    }
}

public boolean put(Item item) {
    if (item == null) {
        throw new IllegalArgumentException("Null items are not allowed");
    }
    lock.lock();
    try {
        if (isPrimaryActive.get()) {
            if (primaryIndex.get() < capacity) {
                primaryBuffer[primaryIndex.getAndIncrement()] = item;
                return true;
            }
        } else {
            if (secondaryIndex.get() < capacity) {
                secondaryBuffer[secondaryIndex.getAndIncrement()] = item;
                return true;
            }
        }
        return false; // Buffer is full
    } finally {
        lock.unlock();
    }
}

public Item get() {
    lock.lock();
    try {
        if (isPrimaryActive.get()) {
            if (primaryIndex.get() == 0) {
                return null;
            }
            return primaryBuffer[primaryIndex.decrementAndGet()];
        } else {
            if (secondaryIndex.get() == 0) {
                return null;
            }
            return secondaryBuffer[secondaryIndex.decrementAndGet()];
        }
    } finally {
        lock.unlock();
    }
}

}
} else {
if (secondaryIndex.get() < capacity) {
secondaryBuffer[secondaryIndex.getAndIncrement()] = item;
}
}
}

/**
* Retrieves and removes the item at the front of the active buffer.
*
* @return The item from the active buffer, or {@code null} if the buffer is empty.
*/
public Item get() {
if (isPrimaryActive.get()) {
if (primaryIndex.get() == 0) {
return null;
}
return primaryBuffer[primaryIndex.decrementAndGet()];
} else {
if (secondaryIndex.get() == 0) {
return null;
}
return secondaryBuffer[secondaryIndex.decrementAndGet()];
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.thealgorithms.datastructures.buffers;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class DoubleBufferTest {

private DoubleBuffer<Integer> buffer;

@BeforeEach
void setUp() {
buffer = new DoubleBuffer<>(5);
}

@Test
void testInitialization() {
assertTrue(buffer.isPrimaryActive());
assertTrue(buffer.isEmpty());
}

@Test
void testPutAndGetFromPrimary() {
buffer.put(1);
buffer.put(2);
buffer.put(3);

assertEquals(3, buffer.get());
assertEquals(2, buffer.get());
assertEquals(1, buffer.get());
assertNull(buffer.get());
}

@Test
void testSwitchBuffers() {
buffer.put(1);
buffer.put(2);
buffer.switchBuffer();

// Now the buffer should be empty as we switched to the secondary buffer
assertTrue(buffer.isEmpty());

buffer.put(3);
assertEquals(3, buffer.get());

// Switch back to primary
buffer.switchBuffer();
assertEquals(2, buffer.get());
assertEquals(1, buffer.get());
}

@Test
void testEmptyBuffer() {
assertNull(buffer.get());
buffer.switchBuffer();
assertNull(buffer.get());
}

@Test
void testIllegalArguments() {
assertThrows(IllegalArgumentException.class, () -> new DoubleBuffer<>(0));
assertThrows(IllegalArgumentException.class, () -> new DoubleBuffer<>(-1));

DoubleBuffer<String> strBuffer = new DoubleBuffer<>(1);
assertThrows(IllegalArgumentException.class, () -> strBuffer.put(null));
}
}