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

最新文章

  1. 你真的会玩SQL吗?三范式、数据完整性
  2. shanquan2的两年三题系列
  3. jQuery 2.0.3 源码分析 钩子机制 - 属性操作
  4. React组件属性部类(propTypes)校验
  5. C#异步方法的使用
  6. java.lang.NoClassDefFoundError: org/apache/ibatis/session/SqlSession
  7. Android ListViewview入门
  8. php Hash Table(一) Hash Table的结构
  9. 关于安装qt之后的qmake命令
  10. Java基础--常用正则匹配符号(必背,必须背,死都要背)
  11. 解决ios下的微信打开的页面背景音乐无法自动播放
  12. ASP.Net MVC利用NPOI导入导出Excel
  13. MAC 命令行工具(Command Line Tools)安装
  14. iOS开发Safari调试WebView页面
  15. jacascript 判断元素尺寸和位置
  16. 深入理解AMQP协议转载
  17. C语言基础:常见循环语句 分类: iOS学习 c语言基础 2015-06-10 21:46 13人阅读 评论(0) 收藏
  18. IDF实验室—不难不易的js加密
  19. python基础学习1-SET 集合
  20. iOS自定义从底部弹上来的View

热门文章

  1. Javascript 补位运算符
  2. SMTP Failed on Process Scheduler
  3. freefilesync 7 使用
  4. Incorrect column name 'productid '
  5. Qt5 Addin 出现问题模块计算机类型“x64”与目标计算机类型“X86”冲突
  6. How to executing direct SQL statements [Axapta, AX4.0, AX2009, AX2012]
  7. python网络画图——networkX
  8. [terry笔记]更改oracle用户名
  9. autolayout 总结
  10. apache 403错