了解Netty 3中MemoryAwareThreadPoolExecutor的行为

时间:2018-05-31 05:26:22

标签: netty threadpool threadpoolexecutor

我想了解Netty 3中MemoryAwareThreadPoolExecutor的行为。

我正在实施java docs中提供的示例,只做了很小的改动。

我的Runnable类

class MyRunnable implements Runnable {

    private final byte[] data;

    public byte[] getData() {
        return data;
    }

    public MyRunnable(byte[] data) {
        this.data = data;

    }

    public void run()  {
        String dataString = new String(data, 0, data.length);
        System.out.println("Started processing data " + dataString);
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
            //Thread.sleep(3000);
        } catch (InterruptedException ie){
            ie.printStackTrace();
        }
        System.out.println("Done processing data " + dataString);
    }
}

MyObjectSizeEstimator类是

class MyObjectSizeEstimator extends DefaultObjectSizeEstimator {
    @Override
    public int estimateSize(Object o) {
        if (o instanceof MyRunnable) {
            return ((MyRunnable) o).getData().length;
        }
        return super.estimateSize(o);
    }
}

Main类是

  public class MemoryAwareThreadPoolExecutorDemo {
      public static void main(String[] args) {
          ThreadPoolExecutor pool = new MemoryAwareThreadPoolExecutor(
                  16, 65536, 1048576, 30, TimeUnit.SECONDS,
                  new MyObjectSizeEstimator(),
                  Executors.defaultThreadFactory());
          String[] dataArray = new String[10];
          for(int i = 0; i < dataArray.length; ++i) {
              dataArray[i] = RandomStringUtils.randomAlphanumeric((i + 1) ) + "   " + i;
          }

          for(int i = 0; i < dataArray.length; ++i) {
              pool.execute(new MyRunnable(dataArray[i].getBytes()));
          }

          while(pool.getActiveCount() != 0) {
              try {
                  TimeUnit.MILLISECONDS.sleep(1000);
              } catch (InterruptedException ie) {
                  ie.printStackTrace();
              }
          }
          pool.shutdown();
      }
  }

我期望主类执行更大的任务。但我发现每次运行程序时,任务总是以随机顺序执行。

程序行为背后的任何解释或原因。

1 个答案:

答案 0 :(得分:1)

MemoryAwareThreadPoolExecutor基本上只知道任务将占用多少内存,并且取决于它处理“背压”。它完全与订购无关。

另请注意,Netty 3很长一段时间都是EOL,你应该使用4.1。