Skip to content

Commit ae39694

Browse files
committed
Add finalizer as "cleanup method of last resort"
1 parent c754ae1 commit ae39694

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

unsafe/src/main/java/org/apache/spark/unsafe/map/BytesToBytesMap.java

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,11 @@ public BytesToBytesMap(MemoryAllocator allocator, long initialCapacity) {
154154
this(allocator, initialCapacity, 0.70);
155155
}
156156

157-
// TODO: consider finalizer.
157+
@Override
158+
public void finalize() {
159+
// In case the programmer forgot to call `free()`, try to perform that cleanup now:
160+
free();
161+
}
158162

159163
/**
160164
* Returns the number of keys defined in the map.
@@ -457,12 +461,18 @@ private void allocate(long capacity) {
457461
/**
458462
* Free all allocated memory associated with this map, including the storage for keys and values
459463
* as well as the hash map array itself.
464+
*
465+
* This method is idempotent.
460466
*/
461467
public void free() {
462-
allocator.free(longArray.memoryBlock());
463-
longArray = null;
464-
allocator.free(bitset.memoryBlock());
465-
bitset = null;
468+
if (longArray != null) {
469+
allocator.free(longArray.memoryBlock());
470+
longArray = null;
471+
}
472+
if (bitset != null) {
473+
allocator.free(bitset.memoryBlock());
474+
bitset = null;
475+
}
466476
Iterator<MemoryBlock> dataPagesIterator = dataPages.iterator();
467477
while (dataPagesIterator.hasNext()) {
468478
allocator.free(dataPagesIterator.next());

0 commit comments

Comments
 (0)