Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top