1. 程式人生 > >java之迴圈引用

java之迴圈引用

在學習java記憶體模型及垃圾回收時提到了引用計數法無法解決迴圈引用的問題,心裡一直在思考怎麼才是迴圈引用。
netty中的迴圈引用的例子。

例如:NioServerSocketChannel類中有內部類NioServerSocketChannelConfig。每一個NioServerSocketChannel例項物件都有全域性變數NioServerSocketChannelConfig的例項物件,而NioServerSocketChannelConfig例項物件在構造的時候也是需要將NioServerSocketChannel例項物件引用進去。也就是NioServerSocketChannel例項物件和NioServerSocketChannelConfig例項物件相互引用了。也就是迴圈引用。

public class NioServerSocketChannel extends AbstractNioMessageChannel
                             implements io.netty.channel.socket.ServerSocketChannel {

    private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
    private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER =
SelectorProvider.provider(); private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioServerSocketChannel.class); //NioServerSocketChannel例項物件的全域性變數ServerSocketChannelConfig的例項 private final ServerSocketChannelConfig config;
public NioServerSocketChannel(ServerSocketChannel channel)
{ super(null, channel, SelectionKey.OP_ACCEPT); //在初始化config的時候將自己(NioServerSocketChannel的例項物件)也傳入了 config = new NioServerSocketChannelConfig(this, javaChannel().socket()); }
private NioServerSocketChannelConfig(NioServerSocketChannel channel, ServerSocket javaSocket) {
    super(channel, javaSocket);
}