码迷,mamicode.com
首页 > 编程语言 > 详细

Java Synchronized Blocks vs. Methods

时间:2015-09-14 15:08:53      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

  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

Java Synchronized Blocks vs. Methods

标签:

原文地址:http://www.cnblogs.com/IcanFixIt/p/4807061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!