Skip to content

Commit

Permalink
add tests for DirectBufferUtils
Browse files Browse the repository at this point in the history
  • Loading branch information
moscicky committed Jun 12, 2023
1 parent 1c3ca8e commit 7652734
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,40 @@ class DirectBufferUtils {
static {
DirectBufferCleaner cleaner;
try {
cleaner = new Java11DirectBufferCleaner();
cleaner = new DirectBufferCleaner();
} catch (ReflectiveOperationException e) {
cleaner = null;
}
CLEANER = cleaner;
}

static boolean supportsReleasing() {
return CLEANER != null;
}


static void release(ByteBuffer buffer) {
try {
if (CLEANER != null && buffer.isDirect()) {
if (supportsReleasing() && buffer.isDirect()) {
CLEANER.clean(buffer);
}
} catch (ReflectiveOperationException e) {
logger.warn("Releasing ByteBuffer failed", e);
}
}

private interface DirectBufferCleaner {
void clean(ByteBuffer buffer) throws ReflectiveOperationException;
}

static class Java11DirectBufferCleaner implements DirectBufferCleaner {
static class DirectBufferCleaner {
private final Object unsafe;
private final Method invokeCleaner;

Java11DirectBufferCleaner() throws ReflectiveOperationException {
DirectBufferCleaner() throws ReflectiveOperationException {
Class<?> clazz = Class.forName("sun.misc.Unsafe");
Field field = clazz.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = field.get(null);
invokeCleaner = clazz.getMethod("invokeCleaner", ByteBuffer.class);
}

@Override
public void clean(ByteBuffer buffer) throws ReflectiveOperationException {
invokeCleaner.invoke(unsafe, buffer);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package pl.allegro.tech.hermes.consumers.consumer.batch;

import org.assertj.core.api.Assertions;
import org.junit.Test;

import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;

public class DirectBufferUtilsTest {
@Test
public void shouldReleaseDirectByteBuffer() {
// given
ByteBuffer buffer = ByteBuffer.allocateDirect(128);

// when & then
assertEquals(DirectBufferUtils.supportsReleasing(), true);
Assertions.assertThatCode(() -> DirectBufferUtils.release(buffer))
.doesNotThrowAnyException();
}

@Test
public void shouldNotReleaseByteBuffer() {
// given
ByteBuffer buffer = ByteBuffer.allocate(128);

// when & then
assertEquals(DirectBufferUtils.supportsReleasing(), true);
Assertions.assertThatCode(() -> DirectBufferUtils.release(buffer))
.doesNotThrowAnyException();
}
}

0 comments on commit 7652734

Please sign in to comment.