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

posted @ 2015-09-14 14:25  林本托  阅读(337)  评论(0编辑  收藏  举报