0

A much better programmer than me informed me that he holds a map of his WebSocket connections with java-websocket in a WeakHashMap. I've looked into that map for myself and it seems perfect since a connection will close without the thread responsible for holding the map being immediately aware thus allowing the closed connections to be garbage collected.

In the docs, I noticed that "The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded.".

Does that mean that a value should never refer to its or any other key at all in the WeakHashMap so not to prevent garbage collection?

And how exactly is a strong reference by a value to its key made?

As an example, I need to hold a list of IP and DNS addresses associated with the key, a connection. How can I ensure that those are not strong references to the key's InetSocketAddress then InetAddress?

1 Answers1

1

Does that mean that a value should never refer to its or any other key at all in the WeakHashMap so not to prevent garbage collection?

A value shouldn't refer to its own key, but it can refer to other keys.

And how exactly is a strong reference by a value to its key made?

If the keys are Strings, and the values have a String data field, you can set that String field to the object's key to create a strong reference from the value to its key.

As an example, I need to hold a list of IP and DNS addresses associated with the key, a connection. How can I ensure that those are not strong references to the key's InetSocketAddress then InetAddress?

An InetAddress doesn't have a strong reference to the connection you got it from. There is no constructor that takes a WebSocket, so there is no way an InetAddress will have a reference to the WebSocket you got it from.

tbodt
  • 16,609
  • 6
  • 58
  • 83
  • Thank you tbodt! Would a `String` of an `InetAddress` value from a `InetSocketAddress` value from the key be a strong reference? Thank you so much in advance! –  Feb 03 '14 at 00:16
  • Thank you again tbodt! I'm still new to Java, so would you mind explaining a little more explicitly with examples how a `List` of `InetAddress` values would and would not be strongly referenced to the key? I'm unsure of how to prevent that since the `InetAddress` comes from the key. I'm using the first half of this answer. http://stackoverflow.com/a/494480/1382306 Thank you again so very much in advance! –  Feb 03 '14 at 00:21
  • 1
    Even though the `InetAddress` comes from the key, the `InetAddress` doesn't have a strong reference to the key. – tbodt Feb 03 '14 at 00:23