© 2008 Cisco Systems, Inc. All rights reserved. Cisco Confidential Presentation_I D 1 Java Concurrency Programming [email protected]
Jan 21, 2016
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 1
Java Concurrency Programming
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 2
Agenda Multi-Thread Introduction
Java Memory Mode
Synchronized
Concurrent Package Introduction
Deadlock
Thread Pool
Multi-thread Anti-pattern
Concurrent Programming Best Practice
Q&A
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 3
Multi-Thread introduction-related conception
What is thread?
Concurrent VS Parallel
Performance VS Multi-Thread
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 4
Multi-Thread introduction -Thread Life Circle
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 5
Multi-Thread introduction -Thread Safe*
Conception 当多个线程访问一个类时,如果不用考虑这些线程在运行环境下的调度和交
替执行,并且不需要额外的同步而且调用方法代码时不需要进行其他协调,这个类的行为依然是正确的,那么称这个类是线程安全的
Atomic operation :在多进程(线程)的操作系统中不能被其它进(线程)打断的操作就叫原子操
作
Visibilityvolatile 的语义 , 其实是告诉处理器 , 不要将我放入工作内存 , 请直接在主存操
作我 因此 , 当多核或多线程在访问该变量时 , 都将直接 操作 主存 , 这从本质上 , 做到了变量共享
锁 多线程中用来保证操作原子性,变量可见性的最有效手段,但也是程序性能,
可伸缩性的主要杀手,原则是能用原子变量或 volatile 替换就用他们替换,能不用锁尽量别用,能用共享锁就别用独占锁,读操作大大多于写操作尽量用读写锁,能采用锁分离策略尽量采用锁分离策略
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 6
线程安全的常见手段a. 让对象无状态b. ThreadLocal 隔离c. 不可变对象天生就是线程安全的d. 让对象只在栈范围内可见e. 用锁保护对象状态
Multi-Thread introduction -Thread Safe*
Thread1 ThreadLocalMap
ThreadLocalMap
ThreadLocalMap
Thread2
Thread3
Key ValueThreadLocal Obj1
ThreadLocal Obj2
ThreadLocal Obj3
Value
Value
Value
ThreadLocal Obj1
ThreadLocal Obj2
ThreadLocal Obj3
Value
Value
Value
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 7
Java Memory Mode
thread1 thread2 thread3 thread4
Heap
Perm gen Heap
code
StackStack StackStack StackStack StackStack
objobj objobj objobj
Native heap
OS task scheduler
CPUcore1 core2 CPUcore1 core2 CPUcore1 core2 CPUcore1 core2
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 8
Synchronized-example1
public synchronized void method4 (){//block
}
public synchronized void method5 (){//block
}
public void method6 (){synchronized (this){
//block}
}
public static synchronized void method1 (){
//block}
public void method2 (){synchronized (this.class){
//block}
}
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 9
Synchronized-example2
public void method1 (){while(status == 1){ wait();}//do something
}
public void method2 (){//do somethingnotifyAll();
}
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 10
Synchronized-notify, notifyAll, wait*
Notify/NotiffyAll
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 11
Concurrent Package Introduction-Atomic Type*
原子类型:AtomicBoolean, AtomicInteger, AtomicIntegerArray, AtomicLong, AtomicReference
原子类型特点:原子类型没有使用锁 , 是无阻塞,通过使用 volatitile 和 CPU 原子原子语义 CAS 实现原子操作
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 12
Concurrent Package Introduction -Synchronizer*
BlockQueue
ConcurrentLinkedQueue
Semaphore
CyclicBarrier
CountDownLatch
FutureTask
Lock
Synchronizer 特征:他们封闭状态,这些状态决定线程执行到某一点时是通过还是被迫等待。
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 13
Concurrent Package Introduction -Executor Framework*
Executor
ExecutorService
CompletionService
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 14
Concurrent Package Introduction -Lock
ReentrantLock
可重入,可中断,可非阻塞,支持公平非公平策略,支持多个条件等待队列 , Synchronized 最佳替代品
ReentrantReadWriteLock
具有 ReentryLock 所有优点,并且允许多线程并发读, Synchronized无法实现同样功能
应用场景:对于那些读多写少的共享对象状态保护
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 15
Concurrent Package Introduction -Lock in DMS ( 1 ) *
ItemState ReadWriteLock
ISIS
ISIS ISIS
Session1-Thread
Session2-Thread
ISIS
Session3-Thread
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 16
Concurrent Package Introduction -Lock in DMS ( 2 ) *
A,B,C
B,C
A,N
DF
Get Lock and check conflict
DB store
wait
CS
notifyThread1
Thread2
Thread3
Thread4
Thread5
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 17
Deadlock
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 18
Deadlock ( 2)Lock writeLock = rwLock.writeLock(); writeLock.lock(); capacityLock.lock(); try { while (capacity > 100) { empty.await(); } capacity++; full.signalAll(); } finally { capacityLock.unlock(); writeLock.unlock(); }
Lock writeLock = rwLock.writeLock(); writeLock.lock(); capacityLock.lock(); try { while (capacity > 100) { empty.await(); } capacity++; full.signalAll(); } finally { capacityLock.unlock(); writeLock.unlock(); }
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 19
Thread Pool 线程池的使用场景 工具类 ThreadPoolExecutor
线程池的风险:–死锁、资源不足、并发错误、线程泄漏、请求过载
线程使用准则–不要对那些同步等待其它任务结果的任务排队。–在为时间可能很长的操作使用合用的线程时要小心。–理解任务。要有效地调整线程池大小,您需要理解正在排队的任务以及它们正在做什么。
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 20
Thread Pool-Servlet Container
Client1
Client2
Servlet Container
thread
threadthread
thread
create
Thread pool
Servlet instance
initialize instance
process request
process request
Instantiate Servlet
Call init() method
Assign a thread to request
Assign a thread to request
Call service method
Call service method
MVCLayer
BusinessLayer
persistentLayer
action
action
action
action
SingletonManager
SingletonManager
Struts2
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 21
Multi-thread Anti-pattern
在构造函数中启动线程不完全的同步在使用某个对象当锁时,改变了对象的引用,导致同步失效
没有在循环中调用 wait()
同步的范围过小或者过大不正确使用 volatile
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 22
Concurrent Programming Best Practice
访问共享数据前问问自己是否需要进行同步 尽量避免一次操作拿多把锁(容易产生死锁) 尽量避免在同步块内调用其他对象的方法 尽可能减少锁持有时间 使用显示锁时一定要遵循 try..finally模式 尽可能使用现有的 1.5 同步工具类进行同步 使用 volatile 只能增加可见性,没有同步语义 不要改变默认线程优先级 尽量减少共享对象的状态谨慎对待 InterruptException ,不要轻易忽略
© 2008 Cisco Systems, Inc. All rights reserved. Cisco ConfidentialPresentation_ID 23
Q&A