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