zoukankan      html  css  js  c++  java
  • Effective Java 72 Don't depend on the thread scheduler

    Principle

    • Any program that relies on the thread scheduler for correctness or performance is likely to be nonportable.

         

      The best way to write a robust, responsive, portable program is to ensure that the average number of runnable threads is not significantly greater than the number of processors. This leaves the thread scheduler with little choice: it simply runs the runnable threads till they're no longer runnable.

         

      Note

      The number of runnable threads isn't the same as the total number of threads, which can be much higher. Threads that are waiting are not runnable.

         

    • Threads should not run if they aren't doing useful work.

      // Awful CountDownLatch implementation - busy-waits incessantly!

      public class SlowCountDownLatch {

      private int count;

      public SlowCountDownLatch(int count) {

      if (count < 0)

      throw new IllegalArgumentException(count + " < 0");

      this.count = count;

      }

      public void await() {

      while (true) {

      synchronized(this) {

      if (count == 0) return;

      }

      }

      }

      public synchronized void countDown() {

      if (count != 0)

      count--;

      }

      }

    • When faced with a program that barely works because some threads aren't getting enough CPU time relative to others, resist the temptation to "fix" the program by putting in calls to Thread.yield.
    • Thread priorities are among the least portable features of the Java platform.

         

      Summary

      Do not depend on the thread scheduler for the correctness of your program. The resulting program will be neither robust nor portable. As a corollary, do not rely on Thread.yield or thread priorities. These facilities are merely hints to the scheduler. Thread priorities may be used sparingly to improve the quality of service of an already working program, but they should never be used to "fix" a program that barely works.

  • 相关阅读:
    单细胞分析实录(13): inferCNV结合UPhyloplot2分析肿瘤进化
    单细胞分析实录(12): 如何推断肿瘤细胞
    单细胞分析实录(11): inferCNV的基本用法
    用网络图展示富集分析
    R绘图(6): 拯救初学者——发表级绘图全能包ggpubr
    R绘图(5): 一文学会桑基图的画法
    db2备份与还原
    SAP R/3系统的启动和关闭
    重启sap过程
    DB2重启数据库实例
  • 原文地址:https://www.cnblogs.com/haokaibo/p/do-not-depend-on-the-thread-scheduler.html
Copyright © 2011-2022 走看看