The second stage: multi-threaded design patterns Details
1、You may not know the singleton design pattern
When optimizing compiler, runtime optimization
2、WaitSet in synchronized monitor
WaitSet (thread lounge)
3、Cpu&Cpu Cache&Mian Memory&Data Bus&Cache
Memory portion 2 has, RAM, ROM
A CPU register, CPU did instruction
Compilation, MOV, JMP, ADD
4、The volatile key word in deep
volatile memory ensures visibility, there is compliant. We can not guarantee atomicity
i=1;
i=1+1;
cpu1->main memory->i->cache i+1 ->cache(2) ->main memory(2)
cpu2->main memory->i->cache i+1 ->cache(2) ->main memory(2)
1) to the data bus lock
bus (data bus, address bus, a control bus)
the LOCK
2) CPU cache coherency protocol
Inter of MESI
The core idea
1) When the CPU write data, if it is found that the variable is shared (that is, there is a copy of the other variables in the cpu), will send a signal to inform the other cpu variable wedding car invalid
2) When other times cpu access to the variable, to help re-acquired memory for
Three important concurrent programming concepts (of AVO)
. 1) atom of A: a plurality of operation or operations are successful or [,] or have failed, for any factors not intermediate interrupt
2) V visibility
3) O has Rank (sequential): reordering is only required final consistency
i=1;
flag = true;
Reordering only require eventual consistency
volatile boolean init;
--------------Thread -1----------------
obj = createObj() 1;
init = true; 2;
--------------Thread -2----------------
whle(!init){
sleep();
}
useTheObj(obj);
-----------------------------------------
Java Memory Model, and CPU cache inconsistency problems
1 atom of
the basic data types of variables and reading assignments is to ensure atomic, either all succeed, yo What else fails, these operations are not interrupted
i=10;
cache 10,memory 10;
a = 10; atomic
b = a; not satisfied, 1.read A; 2.assign to B;
C ++; is not satisfied, 1.read C; 2add; 3assign to C;
C = C + A; not satisfied, 1 .read c; 2add; 3assign to c ;
2, the visibility of
the use of the volatile keyword to ensure visibility
3, ordering
happens-before relationship (collation weight)
1) code execution sequence encoding EDITORIAL transmitted in the preparation in the back
must occur 2) uolock after lock
variable 3) volatile modified, the change variables, first read after write
4) transfer rule, operate a precedes B, B precedes C, then a is certainly prior to the C
startup rule 5) thread, start method certainly before the thread run
interrupts rule 6) threads, interrupt this action , must occur before you capture the action
7) object is destroyed rules, initialization must occur before the Finalize
8) thread the end of the rules, all the operations that take place before the thread death
try{
lock.lock();
}finally{
lock.unlock();
}
The volatile keyword
Once a shared variable is declared volatile, with both semantic layer
1) to ensure the visibility between different threads
2) prohibits reorder, that is, to ensure the orderly
3) does not guarantee atomicity
package com.topxin.designpattern.chapter3;
public class VolatileTest {
//volatile可以保证内存可见性,有顺性。不可以保证原子性
private /* volatile */ static int INIT_VALUE = 0;
private final static int MAX_LIMIT = 50;
public static void main(String[] args) {
new Thread(()->{
int localValue = INIT_VALUE;
while(localValue < MAX_LIMIT) {
if(localValue != INIT_VALUE) {
System.out.printf("The value update to [%d]\n",INIT_VALUE);
localValue = INIT_VALUE;
}
}
},"READER").start();
new Thread(()->{
int localValue = INIT_VALUE;
while(INIT_VALUE < MAX_LIMIT) {
System.out.printf("Update the value to [%d]\n",++localValue);
INIT_VALUE = localValue;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"UPDATER").start();
}
}
read from main memory INIT_VALUE->10
INIT_VALUE=10+1
INIT_VALUE=11
1) to ensure that reordering is not the front into the back of the barrier instruction, nor will the front into the back
2) is forced to modify the operation of the cache write main memory immediately
3) If the operation is a write, it will lead to other CPU in the cache invalidation
volatile usage scenarios
1) state quantity flag
volatile boolean start = true;
while(start){}
void close(){start = false;}
2) consistency before and after the barrier
to sum up
cpu structure substantially write application-t1 CPU ---> shared variables ---> cache (CPU cache coherency protocol of the Inter MESI) ---> main memory
bus (data bus, address bus, a control bus)
JMM general structure (java memory model)
cache coherency protocol
instruction reordering,
happens the before-rule
of the three elements of concurrent programming AVO (atomic (either all succeed or fail), visibility, orderliness)
volatile keyword effect (visibility, order, can not guarantee atomicity)
volatile usage scenarios 1) state quantity flag 2) consistency during barrier
5、Java Class Loader
6、Observer to monitor the Thread lifecycle
Observerable / Subject theme / event source (state) Observer event source is notifier
7、Single Thraded Execution design patten
READ | WRITE | |
READ | N | Y |
reviews | Y | Y |
8, Immutable design pattern (avoid locking, improve efficiency)
Immutable objects must be thread safe inside the task attribute or reference type of property can not be modified
mutable objects are not necessarily unsafe StringBuffer
J2EE servlet is not thread safe
struts1.x Acton is not thread safe
struts2.x Action is thread safe
9, Guarded Suspension protected, first on the queue, and then do one
A breakfast in the kitchen
B is a courier, wall doors, that you express to the request to open the door
Reqeust -> Tomcat httpServer ->doing
Request ->Tomcat httpServer
Queue
10、Balking design pattern
11、Producer-Consumer
12、Read-Write Lock design Pattern
waitset
wait
notifyAll
solution
BooleanLock
syschronized
->Data
read
write
1. read other thread wail enter to the waitset
2. read write 锁分离
concern conflict
1.read read 并行化
2.read write 不允许
3.write write 不允许
ReadWriteLock design pattern
Reader-Writer design pattern
13、Thread-Per-Message Design Pattern
14、Worker Thread Design Pattern
15、Future
Future -> represents a credential future
FutureTask -> your call logic isolation
FutureService -> bridging Future and FutureTask
16, Two-Phase Termination Design Pattern 2 stages End
17, The Thread-Specific Storage thread safe, efficient, thread-safe, versatile, (the problem can be solved in the context of traditional values)
ThreadLocal always current thread as the key value
private static final ThreadLocal<Context> threadLocal = new ThreadLocal<Context>() {
@Override
protected Context initialValue() {
return new Context();
}
};
18、Active Objects
19、Count Down Design Pattern
20、JMM-Java Memory Model