title: Finding out what network sockets are open in the current Java VM
body: <p>I'm writing an end-to-end test that my Java program releases all of its resources - threads, server sockets, client sockets. It's a library, so releasing resources by exiting the JVM is not an option. <a href="https://github.com/orfjackal/jumi/blob/330b8c0e0bb16265fbe4d71588b644eeebfe3811/end-to-end-tests/src/test/java/fi/jumi/test/ReleasingResourcesTest.java" rel="noreferrer">Testing the releasing of threads</a> was easy, because you can ask a <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html" rel="noreferrer">ThreadGroup</a> for all threads in it, but I haven't yet found a good way to get a list of all network sockets that the current JVM is using.</p>
  
  <p><strong>Is there some way to get from a JVM the list of all client and server sockets, similar to netstat?</strong> I'm using <a href="https://netty.io/" rel="noreferrer">Netty</a> with <a href="http://static.netty.io/3.5/api/org/jboss/netty/channel/socket/oio/package-summary.html" rel="noreferrer">OIO</a> (i.e. <a href="http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html" rel="noreferrer">java.net.ServerSocket</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html" rel="noreferrer">java.net.Socket</a>) on Java 7. The solution needs to work on both Windows and Linux.</p>
  
  <p>My first preference would be to ask it from the JVM using pure Java. I tried to look for an MX Bean or similar, but did not find any.</p>
  
  <p>Another option might be to connect to the JVM's profiling/debugging APIs and ask for all instances of Socket and ServerSocket, but I don't know how to do that and whether it can be done without native code (AFAIK, <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jvmti/index.html" rel="noreferrer">JVMTI</a> is native-only). Also, it shouldn't make the tests slow (even my slowest end-to-end test is just 0.5 seconds, which includes starting another JVM process).</p>
  
  <p>If interrogating the JVM doesn't work, a third option would be to create a design which tracks all sockets as they are created. This has the disadvantage of having a possibility of missing some place where sockets are created. Since I'm using Netty, it seems implementable by wrapping <a href="http://static.netty.io/3.5/api/org/jboss/netty/channel/ChannelFactory.html" rel="noreferrer">ChannelFactory</a> and using a <a href="http://static.netty.io/3.5/api/org/jboss/netty/channel/group/ChannelGroup.html" rel="noreferrer">ChannelGroup</a>.</p>