Java Concurrency Programming Summary: Thread security, object sharing

Source: Internet
Author: User
Tags closure event listener volatile

Introduction to the first chapter

Pick a book

    1. Threads share process-wide resources such as memory handles and file handles, but each thread has its own program counter (Programs Counter), stacks, and local variables.

    2. Multiple threads in the same program can also be scheduled to run on multiple CPUs at the same time.

Chapter II Thread Safety

Pick a book

  1. The primary synchronization mechanism in Java is the keyword synchronized, which provides an exclusive locking method, but the term "synchronization" also includes variables of volatile type, explicit locks (Explicit Lock), and atomic variables.

  2. If multiple threads are accessing the same mutable state variable without proper synchronization, the program will have an error. There are three ways to fix this problem:

      • Change state variables are not shared between threads.

      • Modify the state variable to a variable that is immutable.

      • Use synchronization when accessing state variables.

  3. Thread safety definition: When multiple threads access a class, the class always behaves correctly, so it is called thread-safe.

  4. Stateless objects must be thread-safe.

  5. The nature of most race conditions: to make judgments based on a possible failure of observations or to perform a calculation. This type of race condition becomes "check after execution": first observe that a condition is true (for example, file x does not exist), and then take the corresponding action (create file X) based on the observation, but in fact, as you observe the result and start creating the file, The observation may become invalid (another thread created file x during this time), causing a variety of problems (unexpected exceptions, overwritten data, corrupted files, and so on).

  6. Assuming that there are two operations A and B, if from the thread that executes a, when another thread executes B, either all of B is executed, or no B is executed at all, then A and B are atomic to each other. Atomic manipulation means that this operation is an atomic operation for all operations that access the same state, including the operation itself.

  7. In practice, you should use existing thread-safe objects (such as Atomiclong) to manage the state of your classes whenever possible. It is easier to determine the possible state of a thread-safe object and its state transitions than non-thread-safe objects, making it easier to maintain and validate thread security.

  8. To maintain state consistency, you need to update all related state variables in a single atomic operation.

  9. One way to do this is to associate each lock with a get count value and an owner thread. When the count value is 0 o'clock, the lock is considered not to be held by any thread. When a thread requests a lock that is not held, the JVM will note the holder of the lock and set the Get count value to 1. If the same thread acquires the lock again, the count value is incremented, and when the thread exits the synchronization code block, the counter decrements accordingly. When the count value is 0 o'clock, the lock is released.

  10. Not all data requires lock protection, and only variable data that is accessed concurrently by multiple threads needs to be protected by a lock.

  11. Do not hold a lock when the execution takes a long time to calculate or an operation that may not be completed quickly (for example, network IO or console io).

Experience

    1. The state of understanding, I think, is the member variable of the class. Stateless objects are member variables that cannot store data, or can store data, but the data is immutable. Stateless objects are thread-safe. If a member variable exists in a method, it is necessary to perform a thread-safe operation on the member variable.

    2. Do not blindly add synchronized before the method, which can guarantee thread safety, but the concurrency of the method will be weakened, resulting in a method that can support concurrency becomes blocked, resulting in slower program processing speed.

    3. Synchronized surround the code as short as possible, but ensure that all member variables are affected together. Member variables that are not related can be surrounded by multiple synchronized.

Chapter III Sharing of objects

Pick a book

  1. The meaning of locking is not limited to mutex behavior, but also includes memory visibility. To ensure that all threads can see the latest values for shared variables, all threads that perform read or write operations must synchronize on the same lock.

  2. The Java language provides a slightly weaker synchronization mechanism, the volatile variable, that is used to ensure that updates to variables are notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached in registers or in places that are not visible to other processors, so the most recent write value is always returned when reading a variable of type volatile.

  3. The volatile variable is a more lightweight synchronization mechanism than the Synchronized keyword, because it does not perform a lock operation when accessing a volatile variable, and therefore does not cause the execution thread to block.

  4. Volatile variables are often used as flags for an operation to complete, break, or be a state. The semantics of volatile are not sufficient to ensure the atomicity of the increment operation (count++) unless you can ensure that only one thread writes to the variable.

  5. The locking mechanism ensures both visibility and atomicity, while volatile variables only ensure visibility.

  6. You should use a volatile variable only if all of the following conditions are true:

      • The write operation on a variable does not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable.

      • The variable is not included in the non-deformation condition along with other state variables.

      • No lock is required to access the variable.

  7. "Publish (Publish)" An object means that the object can be used in code outside the current scope.

  8. This is known as escaping (Escape) when an object that should not be published is published.

  9. Do not cause this to escape during the construction process.

  10. If you want to register an event listener or a startup thread in a constructor, you can avoid improper construction by using a private constructor and a common factory method (Factory).

  11. Stack closure is a special case of thread closure, where objects are accessed only through local variables in a stack closure.

  12. A more canonical way to maintain thread closeness is to use threadlocal, a class that associates a value in a thread with the object that holds the value.

  13. Threadlocal objects are typically used to prevent the sharing of mutable single-instance objects (Singleton) or global variables.

  14. An object is immutable when the following conditions are true:

      • The state cannot be modified after the object is created.

      • All fields of an object are final types.

      • The object is created correctly (the This reference does not escape during the creation of the object).

  15. Immutable objects must be thread-safe.

  16. To safely publish an object, the reference to the object and the state of the object must be visible to other threads at the same time. A properly constructed object can be safely published in the following ways:

      • Initializes an object reference in the static initialization function.

      • Saves the object's reference to a volatile type of field or Atomicreferance object.

      • Saves a reference to an object in the final type field of a properly constructed object.

      • Saves a reference to an object in a lock-protected domain.

  17. In the absence of additional synchronization, any thread can safely use the fact immutable object that is released safely.

  18. The publication requirements of an object depend on its variability:

      • Immutable objects can be published by any mechanism.

      • Fact-immutable objects must be published in a secure manner.

      • Mutable objects must be published in a secure manner and must be thread-safe or protected by a lock.

  19. When you use and share objects in concurrent programs, you can use some useful strategies, including:

      • Thread is closed. A thread-closed object can only be owned by one thread, and the object is enclosed in that thread and can only be modified by this thread.

      • Read-only sharing. In the absence of additional synchronization, a shared read-only object can be accessed concurrently by multiple threads, but it cannot be modified by any thread. Shared read-only objects include immutable objects and fact-invariant objects.

      • Thread-safe sharing. Thread-safe objects are synchronized internally, so multiple threads can be accessed through the public interface of the object without requiring further synchronization.

      • Protect the object. Protected objects can only be accessed by holding a specific lock. Protection objects include objects encapsulated in other thread-safe objects, and objects that have been published and protected by a particular lock.

Experience

    1. Publish and escape the understanding that a member variable in a class or an object can be referenced by another class to be published, such as a static variable modified with static, or an object that is currently invoking a method. Escaping is an issue where the member variable or object is exposed as being referenced in cases where it should not have been referenced by multithreading, causing its value to be incorrectly modified. In a word, don't arbitrarily expand a class and use the scope of member variables and methods internally. This is also an issue that should be considered in encapsulation.

    2. This escapes: Starting another thread in the constructor's inner class references the object, but this object is not yet constructed and may cause unexpected errors. The workaround is to create a factory method and then set the constructor to a private constructor. A member variable that is modified by the

    3. Final needs to be initialized in the constructor in the constructor, otherwise the member variable cannot be assigned a value after the object is instantiated. When the final decorated member variable is a reference object, the address of the object cannot be modified, but the value of the object can be modified.

    4. The four ways to safely publish an object, such as a reference to Class B in Category A:

      • A static initialization method, such as public Static A A = new A (b); In such a statically factory class, when you reference B, initialize B. The B member variables in the

      • Class A are decorated with volatile B or atomicreferance B. The B member variables in the

      • Class A are decorated with final b b.

      • The method in Class A uses synchronized (lock) {b ...} when used to B. Surrounded.

    5. Fact-immutable objects it is simple to understand that it is technically mutable, but it is an object that is not modified in business logic processing.

Related Article

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.