Thread Safety : When a data type or static method executes in a multi-threaded execution, it can still get the correct behavior without the need for additional collaboration from the caller.
Proper behavior means satisfying specification and maintaining immutability cannot add a time requirement to callers in a precondition (the set () runtime cannot call get ())
Example: iterators, not thread-safe. the specification of an iterator says that you cannot modify a collection while iterating over it. This is a precondition for the time associated with the caller, and iterator does not guarantee that the behavior is correct if it is violated
Four ways to Thread-safe: ① restricts the sharing of mutable variables ② with immutable shared variables ③ The data type of the shared data encapsulation thread security ④ use synchronization to prevent threads from accessing variables at the same time
restricting the sharing of mutable variables : By restricting the data to a single thread, you can avoid the threads competing on variable data. Variable sharing is the main reason for competition
① Local variables are stored in the thread stack, each call has its own copy of the variable, and each thread has its own stack.
② Local Variables If it is a reference to an object, make sure that you cannot reference an object that any other thread can access.
Avoid global variables: global static variables are not automatically restricted by thread access. If you use global static variables, you should indicate that only one thread will use them. It's a good idea to cancel global static variables in a multithreaded environment
Two lines Chengjo call a public static method that returns a class at the same time, generating two instances, which destroys the representation invariance. Retrofit: Adopt a restrictive approach and ensure that only one thread accesses the method, using the synchronized approach
HashMap is not thread safe either.
with immutable shared variables : Use immutable references and data types. Immutable solves the competition caused by sharing mutable data, and simply solves it by making the shared data immutable.
Final variables are immutable references, so variables declared as final can be safely accessed from multiple threads. (can only be read and cannot be written because this security applies only to the variable itself, you must still ensure that the object that the variable points to is immutable)
recall invariance: types are immutable: If an object of type always represents the same abstract value throughout its life cycle
In practice, however, it is permissible to change the rep as long as the changes are not visible to the client and the corresponding abstract values do not change (beneficial mutations) but for concurrency, this hidden change is unsafe, using beneficial changes
The immutable data types must use locks to make themselves thread-safe.
Software constructs concurrency 3 (thread safety)