Netty PooledDirect ByteBuf和ArrayList意外行为

时间:2017-02-01 09:18:25

标签: netty directmemory

这似乎是一个愚蠢的错误,因为我无法找到为什么没有删除所有条目。我正在使用JAVA_OPTS:

  

-XX:MaxDirectMemorySize = 67108864 -Dio.netty.leakDetectionLevel = advanced -D-Dio.netty.allocator.type = pooled -XX:+ UseG1GC -Xms40m -Xmx40m -Dio.netty.allocator.numDirectArenas = 4

以下是完整的代码:

private ByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;

//Configure the arena
//java -Dio.netty.allocator.numDirectArenas=... -Dio.netty.allocator.numHeapArenas=... 
public ByteBuf createObject(int size){
    return alloc.directBuffer(size);
}

public static void main(String[] args) throws InterruptedException {
    ArrayList<ByteBuf> arr = new ArrayList<>();
    try {
        DiameterLoggingConfiguration.initLogger();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ByufferTest bt = new ByufferTest();
    //Total of 66060288 ~ slightly less than 64 mb of direct memory
    for(int i=0;i<64512;i++){
        //Each instance of 1024 bytes
        arr.add(bt.createObject(1024));

    }

    BufferedReader br = new BufferedReader(new
              InputStreamReader(System.in));
    try {
        br.readLine();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Now releasing.."+arr.size());

    for(int i=0;i<arr.size();i++){
        ByteBuf b = arr.remove(i);
        b.release();
    }

    System.out.println("Now array size ="+arr.size());

    Thread.sleep(100000);

}

输出是:

  

现在发布..64512   数组大小= 32256后

不知道只有一半的条目被删除了。仍然有ArrayList中的ByteBuf条目。

1 个答案:

答案 0 :(得分:1)

那是因为你使用:

 for(int i=0;i<arr.size();i++){
    ByteBuf b = arr.remove(i);
    b.release();
}

当您将索引递增0时,这将无效,但也会删除缓冲区。这样你就会跳过缓冲区。

最好使用Queue并使用poll();

 Queue<ByteBuf> arr = new ArrayDeque<>();
 for(;;){
    ByteBuf b = arr.poll();
    if (b == null) {
        break;
    }
    b.release();
}