zoukankan      html  css  js  c++  java
  • Java Synchronized Blocks vs. Methods

      It's possible to synchronize both an entire method and a section of code within a method, and you may wonder which one you should use. To understand which is appropriate in a given situation, it’s important to consider what synchronization really provides.

      Stated simply, synchronization allows you to prevent multithreaded execution of certain portions of a multithreaded application. In other words, synchronization reduces the concurrency of your application’s threads and, if used too extensively, defeats the purpose of using multiple threads. A good rule of thumb is to include as few lines of code as possible within synchronized methods or blocks but only to the extent that you haven’t sacrificed thread safety.

      Adding the synchronized keyword to a method definition is a simple, readable way to provide thread safety, but it’s sometimes not necessary and may be undesirable. For example, if only one or two lines of code within the method really need to be synchronized, you should enclose that code within its own synchronized block instead of synchronizing the entire method. This is particularly true if much of the time devoted to executing that method is spent on code that doesn’t need to be synchronized. In other words, if you synchronize too much of your code, you’ll prevent threads from running when they should be able to run.

      --From 《Pro Java 8 Programming, Third Edition

  • 相关阅读:
    LPC2478中断控制器以及串口详解
    有效三角形的个数
    小于K的两数之和
    和至少为K的最短子数组
    docker: 构建自己的镜像
    判断字符串是否是异位词
    找出字符串中的最长回文
    knuth洗牌算法
    使用adb命令控制anroid手机
    bitmap以及异或运算法
  • 原文地址:https://www.cnblogs.com/IcanFixIt/p/4807061.html
Copyright © 2011-2022 走看看