Index: modules/luni/src/main/java/org/apache/harmony/luni/platform/AbstractMemorySpy.java =================================================================== --- modules/luni/src/main/java/org/apache/harmony/luni/platform/AbstractMemorySpy.java (revision 546816) +++ modules/luni/src/main/java/org/apache/harmony/luni/platform/AbstractMemorySpy.java (working copy) @@ -67,6 +67,10 @@ AddressWrapper wrapper; synchronized (this) { wrapper = memoryInUse.remove(address); + + if (wrapper != null) { + refToShadow.remove(wrapper.wrAddress); + } } if (wrapper == null) { // Attempt to free memory we didn't alloc Index: modules/luni/src/main/java/org/apache/harmony/luni/platform/MappedPlatformAddress.java =================================================================== --- modules/luni/src/main/java/org/apache/harmony/luni/platform/MappedPlatformAddress.java (revision 546816) +++ modules/luni/src/main/java/org/apache/harmony/luni/platform/MappedPlatformAddress.java (working copy) @@ -39,6 +39,7 @@ public final void free(){ if(memorySpy.free(this)){ osMemory.unmap(osaddr, size); + osMemory.free(osaddr); } } Index: modules/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java =================================================================== --- modules/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java (revision 546816) +++ modules/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java (working copy) @@ -585,6 +585,10 @@ long[] handles = new long[length]; int[] offsets = new int[length]; int[] lengths = new int[length]; + + // list of allocated direct ByteBuffers to prevent them from being GC-ed + DirectBuffer[] allocatedBufs = new DirectBuffer[length]; + for (int i = 0; i < length; i++) { ByteBuffer buffer = buffers[i + offset]; if (!buffer.isDirect()) { @@ -593,9 +597,11 @@ directBuffer.put(buffer); directBuffer.flip(); buffer = directBuffer; + allocatedBufs[i] = (DirectBuffer) directBuffer; offsets[i] = 0; } else { offsets[i] = buffer.position(); + allocatedBufs[i] = null; } handles[i] = ((DirectBuffer) buffer).getEffectiveAddress().toLong(); lengths[i] = buffer.remaining(); @@ -611,6 +617,13 @@ completed = true; } finally { end(completed); + + // free temporary direct buffers + for (int i = 0; i < length; ++i) { + if (allocatedBufs[i] != null) { + allocatedBufs[i].free(); + } + } } }