I have project where i'm developing an Android App using a lot of existing C++ code accessed through JNI which opens and closes sockets.
Even though this C++ properly handles the closeing of the sockets it opens, it seems either the Android OS or the JVM keeps around references to those sockets/ports being used until the next GC call.
What happens is if we stop the app and start it again before the next GC call, the app cannot create connections on that same socket/port. If we wait for GC to be called by the OS and then restart the app, it successfully creates the connections. 开发者_运维技巧
Is there a way to manually free up a socket from Android's/the JVM's perspective? Perhaps a socket class utility? A manual call to GC?
The operating system's TCP/IP protocol stack holds TCP ports for two minutes after the application closes them. So if you've had a listening socket that has accepted connections, the port will remain unusable for a couple of minutes.
Before you bind the socket to the listening address, call setsockopt() on the socket with option=SO_REUSEADDR and value of 1.
Try
System.gc();
Docs say...
void java.lang.System.gc() Indicates to the virtual machine that it would be a good time to run the garbage collector. Note that this is a hint only. There is no guarantee that the garbage collector will actually be run.
精彩评论