Java Synchronized Blocks vs. Methods

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.