View
158
Download
0
Category
Preview:
DESCRIPTION
Concurrent Programming in Java. Java 并发编程. 摘要. Java 1.5 并发工具包介绍 实例. Java 并发编程机制. Pre Java 1.5 Thread, Runnable synchronized wait, notify, notifyAll. Java 1.5 Concurrency Utilities. Java 1.5 has comprehensive support for general-purpose concurrent programming - PowerPoint PPT Presentation
Citation preview
Java 并发编程
Concurrent Programming in Java
23/4/20Institute of Computer Software
Nanjing University
1
摘要 Java 1.5 并发工具包介绍 实例
23/4/20Institute of Computer Software
Nanjing University
2
Java 并发编程机制 Pre Java 1.5
Thread, Runnable synchronized wait, notify, notifyAll
23/4/20Institute of Computer Software
Nanjing University
3
Java 1.5 Concurrency Utilities
Java 1.5 has comprehensive support for general-purpose concurrent programming
The support is partitioned into three packages: java.util.concurrent - this provides various classes
to support common concurrent programming paradigms, e.g., support for various queuing policies such as bounded buffers, sets and maps, thread pools etc
java.util.concurrent.atomic - this provides support for lock-free thread-safe programming on simple variables such as atomic integers, atomic booleans, etc.
java.util.concurrent.locks - this provides a framework for various locking algorithms that augment the Java language mechanisms, e.g., read -write locks and condition variables.
23/4/20Institute of Computer Software
Nanjing University
4
Java 并发编程机制 Java 1.5+ Concurrent Utilities
Why? What's new? How to use?
23/4/20Institute of Computer Software
Nanjing University
5
Let’s “listen to” some famous speech!
23/4/20Institute of Computer Software
Nanjing University
6
23/4/20Institute of Computer Software
Nanjing University
7
23/4/20Institute of Computer Software
Nanjing University
8
23/4/20Institute of Computer Software
Nanjing University
9
23/4/20Institute of Computer Software
Nanjing University
10
23/4/20Institute of Computer Software
Nanjing University
11
23/4/20Institute of Computer Software
Nanjing University
12
23/4/20Institute of Computer Software
Nanjing University
13
Thread Pool
Server applications… Thread-per-request approach… Single-background-thread approach… Thread pool offers a solution to both the
problem of thread life-cycle overhead and the problem of resource thrashing.
23/4/20Institute of Computer Software
Nanjing University
14
Risks of using thread pools
Deadlock all pool threads are executing tasks that are
blocked waiting for the results of another task on the queue, but the other task cannot run because there is no unoccupied thread available
Resource thrashing Thread pool size should be tuned properly.
Concurrency errors Thread leakage
occurs when a thread is removed from the pool to perform a task, but is not returned to the pool when the task completes.
Request overload
23/4/20Institute of Computer Software
Nanjing University
15
Guideline for effective use of thread pools
Don't queue tasks that wait synchronously for results from other tasks
Be careful when using pooled threads for potentially long-lived operations
Understand your tasks. To tune the thread pool size effectively, you need to understand the tasks that are being queued and what they are doing.
23/4/20Institute of Computer Software
Nanjing University
16
No need to write your own
java.util.concurrent.* Executor framework
Executor 框架组件提供了一个简单的、标准的、可扩充的类。该框架组件使调用、调度和执行的操作标准化了。它通过一组执行策略为控制异步事务提供了支持。
Executor 接口执行已提交的可以运行的事务。它提供了一条途径,允许我们把事务提交从事务执行机制中分离出来。程序员通常使用 Executor 代替显式地(explicitly) 建立线程。 Executor 接口也提供事务的同步和异步执行。
23/4/20Institute of Computer Software
Nanjing University
17
23/4/20Institute of Computer Software
Nanjing University
18
使用 Executor 接口 public interface Executor
执行已提交的 Runnable 任务的对象。此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节、调度等)分离开来的方法。通常使用 Executor 而不是显式地创建线程。例如:
Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2());
23/4/20Institute of Computer Software
Nanjing University
19
实现 Executor 接口:立即执行
Class DirectExecutor implements Executor{
public void execute(Runnable r) {
r.run(); } }
23/4/20Institute of Computer Software
Nanjing University
20
实现 Executor 接口:异步执行
Class ThreadPerTaskExecutor implements Executor{
public void execute(Runnable r){
new Thread(r).start(); } }
23/4/20Institute of Computer Software
Nanjing University
21
23/4/20Institute of Computer Software
Nanjing University
22
管理一个或多个异步事务的终止和跟踪事务执行的过程
23/4/20Institute of Computer Software
Nanjing University
23
23/4/20Institute of Computer Software
Nanjing University
24
23/4/20Institute of Computer Software
Nanjing University
25
实例 1: TestThreadPool
23/4/20Institute of Computer Software
Nanjing University
26
Notes
合理选择 固定大小:
Executors.newFixedThreadPool(int) 单个后台: Executors.newSingleThreadPool() 可延迟 / 定期执行:
Executors.newScheduledThreadPool(int) 手动配置: new ThreadPoolExecutor(int
corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
…
23/4/20Institute of Computer Software
Nanjing University
27
Notes
必须显式地关闭 线程池必须使用 shutdown 来显式关闭,否则主
线程就无法退出。 shutdown 也不会阻塞主线程。
23/4/20Institute of Computer Software
Nanjing University
28
23/4/20Institute of Computer Software
Nanjing University
29
ScheduledExecutorService
对于调度那些周期性执行的事务非常方便,而周期性执行的事务对于清除工作 ( 例如清除你的应用程序建立的临时文件等等 ) 尤其有用
23/4/20Institute of Computer Software
Nanjing University
30
实例 2: TestScheduledThread
23/4/20Institute of Computer Software
Nanjing University
31
Notes
如何得到 scheduler?final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
使用 schedule, scheduleAtFixedRate,
scheduleWithFixedDelay 同样需要显示关闭
scheduler.shutdown() 但对于 24 小时运行的应用,无须关闭 scheduler
23/4/20Institute of Computer Software
Nanjing University
32
23/4/20Institute of Computer Software
Nanjing University
33
Future
public interface Future<V> Future 表示异步计算的结果。它提供了检查计算是
否完成的方法,以等待计算的完成,并检索计算的结果。
get() 方法:如有必要,等待计算完成,然后检索其结果 ( 如果数据没有加载,就会阻塞直到取到数据 )
get(long timeout, TimeUnit unit) cancel(boolean) 方法:试图取消对此任务的执行
23/4/20Institute of Computer Software
Nanjing University
34
FutureTask
public class FutureTask<V> extends Object implements Future<V>, Runnable
可取消的异步计算。利用开始和取消计算的方法、查询计算是否完成的方法和检索计算结果的方法,此类提供了对 Future 的基本实现。仅在计算完成时才能检索结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。
23/4/20Institute of Computer Software
Nanjing University
35
实例 3: TestFutureTask
23/4/20Institute of Computer Software
Nanjing University
36
实例 4: TestCompletionService
23/4/20Institute of Computer Software
Nanjing University
37
23/4/20Institute of Computer Software
Nanjing University
38
23/4/20Institute of Computer Software
Nanjing University
39
23/4/20Institute of Computer Software
Nanjing University
40
23/4/20Institute of Computer Software
Nanjing University
41
实例 5: TestBlockingQueue
23/4/20Institute of Computer Software
Nanjing University
42
Notes
ArrayBlockingQueue :一个由数组支持的有界队列。
LinkedBlockingQueue :一个由链接节点支持的可选有界队列。
PriorityBlockingQueue :一个由优先级堆支持的无界优先级队列。
DelayQueue :一个由优先级堆支持的、基于时间的调度队列。
SynchronousQueue :一个利用 BlockingQueue 接口的简单聚集( rendezvous )机制
23/4/20Institute of Computer Software
Nanjing University
43
实例 6: TestDelayQueue
23/4/20Institute of Computer Software
Nanjing University
44
Pre-1.5 Java collection classes
Hashtable: an easy-to-use, thread-safe, associative map capability But the thread-safety came at a price -- all
methods of Hashtable were synchronized HashMap
providing an unsynchronized base class and a synchronized wrapper -- Collections.synchronizedMap.
23/4/20Institute of Computer Software
Nanjing University
45
Two principal deficiencies
It is an impediment to scalability, because only one thread can access the hash table at a time.
It is insufficient to provide true thread safety, in that many common compound operations still require additional synchronization.
23/4/20Institute of Computer Software
Nanjing University
46
23/4/20Institute of Computer Software
Nanjing University
47
ConcurrentHashMap
putIfAbsent() :只有在 map 不包含这个键时,才能将键加入到 map 中。如果 map 已经包含这个键,那么这个键的现有值就会保留。 putIfAbsent() 方法是原子的。
等价的 putIfAbsent() 代码if (!map.containsKey(key)) { return map.put(key, value); } else {
return map.get(key); }
23/4/20Institute of Computer Software
Nanjing University
48
ConcurrentHashMap
remove() :只有当键映射到指定的值时才从 map 中删除这个键。如果不匹配,那么就不删除这个键,并返回 false 。如果值匹配键的当前映射内容,那么就删除这个键。
等价的 remove() 代码if (map.get(key).equals(value)){
map.remove(key); return true; } else { return false; }
23/4/20Institute of Computer Software
Nanjing University
49
CopyOnWriteArrayList
copy-on-write pattern: to maintain a consistent snapshot of an object, you rely on immutability to eliminate the need for synchronization when you need to coordinate readings of separate but related attributes
CopyOnWriteArrayList and CopyOnWriteArraySet, work best when the read operations typically far outweigh the write operations.
23/4/20Institute of Computer Software
Nanjing University
50
实例 7: TestCopyOnWrite
23/4/20Institute of Computer Software
Nanjing University
51
23/4/20Institute of Computer Software
Nanjing University
52
23/4/20Institute of Computer Software
Nanjing University
53
23/4/20Institute of Computer Software
Nanjing University
54
23/4/20Institute of Computer Software
Nanjing University
55
23/4/20Institute of Computer Software
Nanjing University
56
23/4/20Institute of Computer Software
Nanjing University
57
23/4/20Institute of Computer Software
Nanjing University
58
实例 8: ConditionTester
23/4/20Institute of Computer Software
Nanjing University
59
23/4/20Institute of Computer Software
Nanjing University
60
23/4/20Institute of Computer Software
Nanjing University
61
实例 9: TestCyclicBarrier
23/4/20Institute of Computer Software
Nanjing University
62
实例 10: TestCountDownLatch
23/4/20Institute of Computer Software
Nanjing University
63
实例 11: TestSemaphore
23/4/20Institute of Computer Software
Nanjing University
64
23/4/20Institute of Computer Software
Nanjing University
65
23/4/20Institute of Computer Software
Nanjing University
66
23/4/20Institute of Computer Software
Nanjing University
67
23/4/20Institute of Computer Software
Nanjing University
68
作业(本次作业不用提交)学习、研究 Doug Lea 的
java.util.concurrent 工具包的实现。尝试用这个工具包解决哲学家用餐问题。
23/4/20Institute of Computer Software
Nanjing University
69
Recommended