Home > Software design >  Some questions about jdk nio SelectionKey
Some questions about jdk nio SelectionKey

Time:12-16

Recently, I had a problem reading the jdk 1.8 nio source code. I wonder what the difference between these two properties is? Based on my query, some people say that publicKeys is a proxy enhancement to keys, but I found that it is possible to add elements to keys, but publicKeys is immutable, how should this be understood.

public abstract class SelectorImpl extends AbstractSelector {
    protected HashSet<SelectionKey> keys = new HashSet();
    private Set<SelectionKey> publicKeys;

    
}

CodePudding user response:

Assuming you are referring to sun.nio.ch.SelectorImpl, publicKeys is declared as private and assigned as follows in the constructor: publicKeys = Collections.unmodifiableSet(keys).

Taking a look at Collections#unmodifiableSet(Set) we see that this provides "read-only" access to its argument. It does NOT behave like a copy constructor, i.e. copying element references and providing a static view of the original at the time the method is invoked. Rather, it provides a dynamic Set view of the original, where all Set modification methods (e.g. add, clear) throw an exception.

  • Related