【问题标题】:understanding the behavior of MemoryAwareThreadPoolExecutor in Netty 3理解 Netty 3 中 MemoryAwareThreadPoolExecutor 的行为
【发布时间】:2018-11-10 01:08:17
【问题描述】:

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

我正在实现java docs 中提供的示例示例,并稍作改动。

我的可运行类

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);
    }
}

主类是

  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();
      }
  }

我希望主类执行规模较大的任务。但是我看到每次运行程序时任务总是以随机顺序执行。

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

【问题讨论】:

    标签: netty threadpool threadpoolexecutor


    【解决方案1】:

    MemoryAwareThreadPoolExecutor 基本上只知道任务将占用多少内存,并根据它处理“背压”。根本与订购无关。

    还要注意,Netty 3 长期 EOL,你应该使用 4.1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 2018-03-12
      • 2019-09-16
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      相关资源
      最近更新 更多