High concurrency-thread-Safe handling (1)-code explanation of variable integer classes

Source: Internet
Author: User

When dealing with thread safety, you first need to introduce the annotations package

We're talking about thread safety. In fact, the nature of the variable is the atomicity of the state changes, in any system, variables everywhere, so in the face of high concurrency multithreaded business code processing pay special attention to thread safety, is also a lot of programmers are easy to ignore the place


1. General non-safe wording

public class Unsynchronizedinteger {
private int value;
public synchronized int get () {
return value;
}
Public synchronized void set (int value) {
This.value = value;
}
}

Comments: Such a way of writing, for single-threaded can also be said of the past, but the real scene, especially the core business code, it is not possible not to involve high concurrency under the multithreading, in this case, the value is likely to be lost and invalid (this failure will not appear in the regular test, It's hard to find the fault when it comes up.)

2 "thread safe and correct notation:

@ThreadSafe
public class Synchronizedinteger {
@GuardedBy ("this") private int value;

public synchronized int get () {
return value;
}
Public synchronized void set (int value) {
This.value = value;
}
}

High concurrency-thread-Safe handling (1)-code explanation of variable integer classes

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.