Seems like when there is IO operations waiting for external service lots of thread are waiting at sun.misc.Unsafe.park. This contributed to native memory buildup that does not gets cleared. How does this Native memory gets cleared. Does it gets cleared after some time automatically
Asked
Active
Viewed 133 times
0
-
`Unsafe.park` does not contribute to the native memory footprint. Please, clarify what you mean, preferably with a code sample and with the output of diagnostic tools. – apangin Sep 15 '19 at 06:48
-
Direct ByteBuffers register a [Cleaner](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/Cleaner.html) object that releases the associated native memory when the ByteBuffer becomes unreachable. – apangin Sep 15 '19 at 06:51
-
There's this : https://stackoverflow.com/questions/30458195/does-gc-release-back-memory-to-os although that's a few years back (Java 8 timeframe), but IIRC later versions of Java have some improvements – racraman Sep 15 '19 at 06:58
1 Answers
0
Using thread-per-connction IO incurs the following memory costs:
- thread stack
ByteBuffer
orbyte[]
passed to the read/write/send/receive method- potentially a bounce buffer (an openjdk implementation detail) since the syscalls expect a fixed buffer while the java data structures can be moved by the GC
- additional abstractions and application on top of the IO functions kept alive for the lifetime of the connection
- kernel socket memory
- can be tweaked a little by adjusting the
-Xss
argument. A complete fix requires multiplexing multiple connections on fewer thread via nonblocking/asynchronous IO.AsynchronousSocketChannel
makes this easy to use for TCP sockets,HttpClient
for HTTP. For other protocols you'll need to look for libraries implementing async IO. - is unavoidable, but depending on application design there may be room for optimization. e.g. if you were to send a 1GB file you don't need a 1GB buffer, you could read it chunk by chunk with smaller buffers
- can be avoided by passing
DirectByteBuffer
instances to IO methods. using async IO also reduces the total number of buffers that need to be used concurrently - not specific to IO, thus general memory footprint optimization advice applies
- generally shouldn't be an issue since the kernel auto-sizes them. but of course keeping thousands of sockets open longer than necessary will still have an impact
Overall the JVM should clean up the native resources needed for IO eventually, but when that happens may depend on how long you keep the java objects that depend on those native resources alive.

the8472
- 40,999
- 5
- 70
- 122