java / intermediate
Snippet
Managing Off-Heap Direct ByteBuffers in Prototype Bean Lifecycles
Allocating off-heap memory through `ByteBuffer.allocateDirect` circumvents standard Java garbage collection pressure, but requires disciplined manual lifecycle management. In Spring, prototype-scoped beans that allocate native memory can implement `DisposableBean` to provide cleanup hooks. While Spring does not manage the complete lifecycle of prototype beans automatically, explicit destruction calls invoke `destroy()` to clear native memory references.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Component@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)public class DirectMemoryBufferPool implements DisposableBean {private ByteBuffer offHeapBuffer;public void initializeBuffer(int capacityBytes) {this.offHeapBuffer = ByteBuffer.allocateDirect(capacityBytes);}public ByteBuffer acquireBuffer() {return this.offHeapBuffer.duplicate();}@Overridepublic void destroy() {if (this.offHeapBuffer != null && this.offHeapBuffer.isDirect()) {this.offHeapBuffer.clear();this.offHeapBuffer = null;}}}
spring
Breakdown
1
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Ensures a fresh buffer instance is created per request instead of sharing a global singleton.
2
this.offHeapBuffer = ByteBuffer.allocateDirect(capacityBytes);
Allocates native unmanaged off-heap memory outside the standard JVM heap space.
3
public void destroy()
DisposableBean lifecycle hook executed during manual cleanup to release object references.