Java program how to ensure the safe operation of multi-threaded?

Security thread is reflected in:

  • Atomicity: one or more operations during CPU execution is not interrupted characteristics
  • Visibility: modify a shared variable thread, another thread can see immediately
  • Ordering: the program execution sequence performed in the order code

Cause security problems thread:

  • Cache cause visibility problems
  • Thread switch cause problems atoms
  • Compiler optimization problem caused orderliness

Java solution given by:

  • - Atom JDK Atomic beginning, synchronized, LOCK, can solve the problem of atomicity
  • synchronized, volatile, LOCK, can solve the visibility problem
  • Happens-Before ordering rules may solve the problem

Happens-Before rules:

  Because jvm will optimize the code is compiled, instruction reordering of the situation will be, in order to avoid impact on the safety of concurrent programming compiler optimization, you need to define happens-before rule prohibiting compiler optimization scenarios to ensure the correctness of concurrent programming.

  1. Program sequence rules: refers to a thread in accordance with the order of the program code, the latter preceding code results can be seen the code runs.
  2. Transitivity rule: transitivity, means that if A Happens-Before to B, B Happens-Before to C, then A Happens-Before to C. This is well understood. That is, if the operation result of A to B is visible, the operation result B to C with visible white words, the operation result A to C is also visible.
  3. Rule volatile variables: refers to a write operation to the volatile variables, Happens-Before subsequent read operation of the volatile variables.
  4. Refers to a lock unlocking Happens-Before subsequent locking of the lock in.
  5. Thread start () Rule: refers to the main thread after thread B A promoter, the sub-thread B can see the operation before initiating a main thread thread B.
  6. Thread join () rule: refers to the calling thread interrupt A thread B () method, Happens-Before thread B to detect the interrupt event (that is, Thread.interrupted () method). This is also very easy to understand.
  7. Thread interrupt () rule: refers to the calling thread interrupt A thread B () method, Happens-Before thread B to detect the interrupt event (that is, Thread.interrupted () method). This is also very easy to understand.
  8. finalize () Rule: refers to the execution of the object constructor, ending at the start Happens-Before finalize () method.

Guess you like

Origin www.cnblogs.com/jxxblogs/p/11884679.html