java / beginner
Snippet
Memory Cleanup and Resource Release with @PreDestroy
The @PreDestroy annotation specifies a lifecycle callback that Spring executes right before taking a bean out of service. This allows clearing heavy in-memory data structures and releasing resources to prevent memory leaks during container shutdowns.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
@Componentpublic class BufferManager {private final byte[] memoryBuffer = new byte[1024 * 1024];@PreDestroypublic void releaseResources() {java.util.Arrays.fill(memoryBuffer, (byte) 0);System.out.println("Memory buffer cleared before container shutdown.");}}
spring
Breakdown
1
private final byte[] memoryBuffer = new byte[1024 * 1024];
Allocates a 1 MB byte array in memory when the Spring component is instantiated.
2
@PreDestroy
Marks the method to be executed by Spring when the application context is shutting down.