It's possible to synchronize both an entire method and a sections of code within a method, and you could wonder which one you should use. To understand which are 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 applic ation. In other words, synchronization reduces the concurrency of your application ' s threads and, if used too extensively, defeat s 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 extent that haven ' t sacrificed thread safety.
Adding The Synchronized keyword to a method definition are a simple, readable-to-provide thread safety, but it's so Metimes not necessary and is undesirable. For example, if only one or both lines of code within the method really need to is synchronized, you should enclose that CO De within its own synchronized block instead of synchronizing the entire method. This is particularly true if much of the time devoted to executing, is spent on code that doesn ' t need to be SY Nchronized. In other words, if you synchronize too much of your code, you'll prevent threads from running when they should is able to Run.
--from "Pro Java 8 programming, Third Edition"
Java Synchronized Blocks vs. Methods