"Notes" Java concurrent programming combat

Source: Internet
Author: User

  1. Thread-related issues: a) security issue B) activity issues C) Performance issues
  2. The key to writing thread-safe code is to manage state access operations, especially access to shared and mutable states
  3. The main synchronization mechanism in Java is the keyword synchronized, which provides an exclusive locking method, the term "synchronization" also includes variables of volatile type, display locks and atomic variables
  4. When writing concurrent applications, one of the correct programming methods is to make the code run correctly first, and then increase the speed of the code.
  5. A program that consists entirely of thread-safe classes is not necessarily threaded, and can also contain non-thread-safe classes in the thread-safe class
  6. Thread safety: When multiple threads access a class, this class always shows the correct behavior, then it is called thread-safe.
  7. Stateless objects must be thread-safe
  8. Stateless object, atomic, state condition, conforming operation
  9. When the correctness of a calculation depends on the alternating execution timing of multiple threads, the conditions of the condition occur. The most common type of condition is the "check and execute" operation, which determines the next action through a potentially defunct observation.
  10. counters, which can be implemented through existing thread-safe classes such as Atomiclong
  11. In practice, you should use existing thread-safe objects (such as Atomiclong) to manage the state of the class as much as possible
  12. A synchronous code block consists of two parts: an object reference as a lock, and a block of code that is protected by this lock.
  13. Re-entry means that the operation granularity of acquiring a lock is "thread", not "call"
  14. Each shared and mutable variable should be protected by only one lock, which is what the maintainer knows is the lock
  15. A common locking convention is to encapsulate all mutable states inside an object and synchronize all code paths that access the mutable state through the object's built-in lock, so that no concurrent access occurs on the object, such as vector
  16. Not all data requires lock protection, and only variable data that is accessed concurrently by multiple threads needs to be protected by a lock
  17. For each immutability condition that contains multiple variables, all of the variables involved need to be protected by the same lock
  18. Whether you are performing a computationally intensive operation or performing a potentially blocking operation, if you hold the lock for too long, you will have an active or performance problem, and you must not hold the lock when the execution takes longer to calculate or the operation that may not be done quickly (such as I/O)
  19. As long as data is shared among multiple threads, the correct synchronization is used
  20. Visibility issues, resulting in failure values, non-atomic 64-bit operational issues, using volatile declarations or synchronous protection
  21. 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.
  22. The correct use of volatile variables includes ensuring the visibility of their own state, ensuring the visibility of the state of the objects they reference, and identifying the occurrence of some important program life-cycle events (for example, initialization or shutdown)
  23. Debug prompt, specify the –SERVCR command when starting the JVM, more optimizations will be made, such as the non-modified variables in the loop are promoted to the outside of the loop, the wireless loop is discovered
  24. The locking mechanism ensures both visibility and atomicity, while volatile variables only ensure visibility
  25. The volatile variable should be used only if all conditions are met: a) The write operation on the variable does not depend on the current value of the variable, or can ensure that only a single thread updates the value of the variable B) that the variable is not incorporated into the invariant condition with other state variables C) does not require locking when accessing variables
  26. Synchronization is often required when accessing shared mutable data. One way to avoid using synchronization is to not share data. If data is accessed only in single-wire range, no synchronization is required. This technique is called thread closure
  27. Thread closure technology: ad-hoc/Stack closed/threadlocal class
  28. Another way to meet synchronization requirements is to use immutable objects: An object cannot be modified after it has been created. Immutable objects have only one state, and have constructors to control
  29. Immutable: a) state not modifiable B) All domains are final type C) correct construction process
  30. Mutable objects must be published in a secure manner, which usually means that the thread of the object must be published and used to synchronize
  31. 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 way: a) initialize an object reference B in a static initialization function) Save the object's reference to a volatile type of domain or Atomicreferance object c) Save the object's reference to the final type field of a properly constructed object D) Save the object's reference to a lock-protected domain
  32. To publish an object securely through a container: a) by placing a key or value in Hashtable, Synchronizedmap, or Concurrentmap B) by placing an element into the vector, copyonwritearraylist, Copyonwritearrayset, Synchronizedlist, or Synchronizedset C) by placing an element in a blockingquere or concurrentlinkedquere
  33. When you get a reference to an object, you need to know what can be done on that reference. Whether you need to get a lock before using it, whether you can modify its state, or only read it
  34. When you use and share objects in concurrent programs, you can use some useful policies: a) thread-closed B) Read-only sharing c) thread-safe sharing d) Protecting objects
  35. In the process of designing a thread-safe class, you need to include three basic elements: a) Find out all the variables that make up the state of the object B) Find out the invariant condition of the constraint state variable C) Establish concurrent access management policy for object state
  36. Various built-in mechanisms (including wait and notification mechanisms) that wait for a condition to be true are closely related to the built-in locking mechanism
  37. Encapsulating data inside an object allows data access to be restricted to the methods of the object, making it easier to ensure that threads always hold the correct locks when accessing data
  38. Using a private lock object instead of an object's built-in lock (or any other publicly accessible lock), the lock can be encapsulated so that the customer code cannot be locked, but the customer code can access the lock by means of a common method
  39. If a state variable is thread-safe and does not have any invariant conditions to constrain its value, there is no state transition that is not allowed in the operation of the variable, so it is safe to publish the variable
  40. Synchronized, volatile, or any one of the thread-safe classes corresponds to a synchronization policy that ensures data integrity during concurrent access
  41. There are several aspects to consider when designing a synchronization strategy, for example, which variables are declared as volatile types, which are protected with locks, which locks protect those variables, which must be immutable or enclosed in threads, which operations must be atomic operations, and so on.
  42. Thread safety for ServletContext, HttpSession, or datasource
  43. The synchronization container moves all access to the container state to implement their thread security. The cost of this approach is to severely reduce concurrency, which severely reduces throughput when multiple threads compete for a lock on a container
  44. Replacing synchronous containers with concurrent containers can greatly improve scalability and reduce risk; Concurrenthashmap, Copyonwritearraylist, Copyonwritearrayset, Blockingqueue
  45. The blocking queue can be used as a synchronization tool class, and other types of synchronization tool classes include semaphores (Semaphore), Fences (Barrier), and latching (Latch)
  46. Latching can delay the progress of a thread until it reaches the terminating state, and it can be used to ensure that certain activities continue until other activities are completed.
  47. Futuretask represents a calculation that is implemented by callable, which is equivalent to a runnable,futuretask that produces a result that represents an asynchronous task in the executor framework and can also be used to represent some long-time computations
  48. The count semaphore is used to control the number of simultaneous accesses to a particular resource, or the number of simultaneous execution of a specified operation, which can be used to implement a resource pool, such as a database connection pool
  49. Fences are similar to latching, which can block a group of threads until an event occurs. The key difference between fencing and latching is that all threads must reach the fence position at the same time to continue execution, latching for waiting events, and fences waiting for other threads
  50. Concurrency tips: a) mutable state is critical B) declare the domain as final, unless you want them to be variable C) The immutable object must be thread-safe D) encapsulation helps manage complexity e) protect each variable with a lock f) when protecting all variables in the same invariant condition, To use the same lock g) during a composite operation, to hold the lock h) if there is no synchronization mechanism when accessing the same mutable variable from multiple threads, then the program will have a problem i) do not pretend to be smart enough to infer that you do not need to use synchronization J to consider thread safety in the design process, or in the document explicitly stating that it is not thread-safe k) document the synchronization policy
  51. Executing a task in a thread pool is more advantageous than assigning one for each task more: a) reusing threads, allocating significant overhead incurred during thread creation and destruction B) when a request arrives, the worker thread already exists, does not delay the execution of the task due to waiting to create the thread, improves responsiveness C) by sizing the thread pool, You can create enough threads to keep the processor busy, and you can prevent too many threads from competing with each other to make the application run out of memory or fail
  52. By using executor, you can implement a variety of tuning, management, monitoring, logging, error reporting, and other features that are difficult to add if you don't use the task execution framework
  53. The Executor framework decouples task submissions from execution policies and supports several different types of execution strategies. When you need to create a thread to perform a task, consider using the executor
  54. There is no secure preemptive method in Java to stop a thread, so there is no secure preemptive method to stop the task. There are only a few collaborative mechanisms that enable the task and code to cancel the request to follow a negotiated protocol: a) the "requested cancellation" flag
  55. The correct understanding of an interrupt operation is that it does not actually interrupt a running thread, but simply makes an interrupt request, which is then interrupted by the thread at the next appropriate moment (also known as a cancellation point), usually the most logical way to implement cancellation
  56. The most reasonable interrupt policy is some form of thread-level (thread-level) cancel operation or service-level (Service-level) Cancel operation: Exit as soon as possible, clean up if necessary, notify an owner thread that has exited
  57. A task does not execute in its own thread, but rather in a thread owned by a service (such as a thread pool), which is that most of the blocking library functions simply throw interruptedexception as an interrupt response, and they never run in a thread owned by themselves. Therefore, they implement the most reasonable cancellation policy for the task or library code: Exit the execution process as soon as possible and pass the interrupt information to the caller, so that the upper code in the call stack can take further action
  58. When canceling a producer-consumer operation, it is necessary to cancel both the producer and the consumer
  59. A closed hook is a thread registered through Runtime.addshutdownhook but not yet started.
  60. Threads can be divided into two types: normal thread and daemon thread. All threads created at the start of the JVM, except the main thread, are daemon threads (such as the garbage collector and other threads that perform worker work). When a new thread is created, the new thread inherits the daemon state of its thread, so by default all threads created by the main thread are normal threads. The difference between a normal thread and a daemon thread is only the action that occurs when the thread exits
  61. Deadlock: Excessive locking may result in "Lock sequence deadlock", using the thread pool and semaphores to limit the use of resources, which may result in "resource deadlock"
  62. In concurrent programs, the most significant threat to scalability is the exclusive way of resource locks
  63. There are two factors that will affect the likelihood of competition in the lock: the frequency of the request for the locks, and the time of each hold of the lock
  64. The Amdahl law tells us that the scalability of the program depends on the proportion of code that must be executed serially in all code
  65. Increased scalability can be achieved by reducing the holding time of locks, reducing the granularity of locks, and using non-exclusive locks or non-blocking locks instead of exclusive locks
  66. When a class is loaded for the first time, the JVM executes it by interpreting the bytecode. At some point, if a method runs enough times, the dynamic compiler compiles it into machine code, and when the compilation is complete, the execution of the code changes from interpreted execution to direct execution.
  67. A fair lock should be used when the lock is held for a relatively long time, or if the average time interval for the request lock is longer. In these cases, the throughput boost caused by "queue jump" may not occur
  68. Reentrantlock can be used as an advanced tool in situations where some built-in locks do not meet the requirements. You should use Reentrantlock when you need some advanced features, including: Timed, polled, and interruptible lock acquisition operations, fair queues, and non-block locks. Otherwise, you should prioritize the use of synchronized
  69. Read/write Lock: A resource can be accessed by multiple read operations, or accessed by a write operation, but not both
  70. You can use the underlying mechanisms provided by the Java language and the class library to construct your own synchronization mechanisms, including built-in conditional queues, displayed condition objects, and abstractqueuedsynchronized frameworks
  71. When a conditional wait is used (object.wait or condition.await): a) The pass-through has a conditional predicate-including some test of the state of the object, the thread must first pass these test B before executing, and test the conditional verb before calling wait. and test again when returning from wait C) call wait D in a loop to ensure that the various state variables that make up the conditional predicate are protected with the lock associated with the conditional queue E) When calling a method such as wait, notify, or Notifyall, be sure to hold the lock F associated with the conditional queue) Do not release the lock after the conditional verb is checked and before the appropriate action is started
  72. Active failure: Deadlock, live lock, lost signal. Lost signal: The thread must wait for a condition that is already true, but does not check the conditional predicate before it begins to wait
  73. In most cases it should be limited to select Notifyall instead of individual notify. Only if two conditions are met, can you use a single notify instead of a notifyall:a) all the waiting threads are the same type, only one conditional predicate is associated with the conditional queue, and each thread will perform the same action after returning from wait b) Single-step out, each notification on the condition variable, A maximum of one thread can be awakened to execute
  74. For each dependent state operation, and for each operation that modifies the dependent state of other operations, an ingress protocol and an egress protocol are defined, and the Ingress protocol is the conditional predicate for the operation, and the egress protocol includes checking all state variables modified by the operation and confirming that they are using some other conditional predicate to become true. If yes, notifies the relevant conditional queue

"Notes" Java concurrent programming combat

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.