69
Java 并并并并 Concurrent Programming in Java 22/3/30 Institute of Computer Software Nanjing University 1

Concurrent Programming in Java

Embed Size (px)

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

Page 1: Concurrent Programming in Java

Java 并发编程

Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

1

Page 2: Concurrent Programming in Java

摘要 Java 1.5 并发工具包介绍 实例

23/4/20Institute of Computer Software

Nanjing University

2

Page 3: Concurrent Programming in Java

Java 并发编程机制 Pre Java 1.5

Thread, Runnable synchronized wait, notify, notifyAll

23/4/20Institute of Computer Software

Nanjing University

3

Page 4: Concurrent Programming in Java

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

Page 5: Concurrent Programming in Java

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!

Page 6: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

6

Page 7: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

7

Page 8: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

8

Page 9: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

9

Page 10: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

10

Page 11: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

11

Page 12: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

12

Page 13: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

13

Page 14: Concurrent Programming in Java

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

Page 15: Concurrent Programming in Java

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

Page 16: Concurrent Programming in Java

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

Page 17: Concurrent Programming in Java

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

Page 18: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

18

Page 19: Concurrent Programming in Java

使用 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

Page 20: Concurrent Programming in Java

实现 Executor 接口:立即执行

Class DirectExecutor implements Executor{

public void execute(Runnable r) {   

r.run();    }   }

23/4/20Institute of Computer Software

Nanjing University

20

Page 21: Concurrent Programming in Java

实现 Executor 接口:异步执行

Class ThreadPerTaskExecutor implements Executor{   

public void execute(Runnable r){   

new Thread(r).start();    }   }

23/4/20Institute of Computer Software

Nanjing University

21

Page 22: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

22

管理一个或多个异步事务的终止和跟踪事务执行的过程

Page 23: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

23

Page 24: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

24

Page 25: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

25

Page 26: Concurrent Programming in Java

实例 1: TestThreadPool

23/4/20Institute of Computer Software

Nanjing University

26

Page 27: Concurrent Programming in Java

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

Page 28: Concurrent Programming in Java

Notes

必须显式地关闭 线程池必须使用 shutdown 来显式关闭,否则主

线程就无法退出。 shutdown 也不会阻塞主线程。

23/4/20Institute of Computer Software

Nanjing University

28

Page 29: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

29

Page 30: Concurrent Programming in Java

ScheduledExecutorService

对于调度那些周期性执行的事务非常方便,而周期性执行的事务对于清除工作 ( 例如清除你的应用程序建立的临时文件等等 ) 尤其有用

23/4/20Institute of Computer Software

Nanjing University

30

Page 31: Concurrent Programming in Java

实例 2: TestScheduledThread

23/4/20Institute of Computer Software

Nanjing University

31

Page 32: Concurrent Programming in Java

Notes

如何得到 scheduler?final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

使用 schedule, scheduleAtFixedRate,

scheduleWithFixedDelay 同样需要显示关闭

scheduler.shutdown() 但对于 24 小时运行的应用,无须关闭 scheduler

23/4/20Institute of Computer Software

Nanjing University

32

Page 33: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

33

Page 34: Concurrent Programming in Java

Future

public interface Future<V> Future 表示异步计算的结果。它提供了检查计算是

否完成的方法,以等待计算的完成,并检索计算的结果。

get() 方法:如有必要,等待计算完成,然后检索其结果 ( 如果数据没有加载,就会阻塞直到取到数据 )

get(long timeout, TimeUnit unit) cancel(boolean) 方法:试图取消对此任务的执行

23/4/20Institute of Computer Software

Nanjing University

34

Page 35: Concurrent Programming in Java

FutureTask

public class FutureTask<V> extends Object implements Future<V>, Runnable

可取消的异步计算。利用开始和取消计算的方法、查询计算是否完成的方法和检索计算结果的方法,此类提供了对 Future 的基本实现。仅在计算完成时才能检索结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。

23/4/20Institute of Computer Software

Nanjing University

35

Page 36: Concurrent Programming in Java

实例 3: TestFutureTask

23/4/20Institute of Computer Software

Nanjing University

36

Page 37: Concurrent Programming in Java

实例 4: TestCompletionService

23/4/20Institute of Computer Software

Nanjing University

37

Page 38: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

38

Page 39: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

39

Page 40: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

40

Page 41: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

41

Page 42: Concurrent Programming in Java

实例 5: TestBlockingQueue

23/4/20Institute of Computer Software

Nanjing University

42

Page 43: Concurrent Programming in Java

Notes

ArrayBlockingQueue :一个由数组支持的有界队列。

LinkedBlockingQueue :一个由链接节点支持的可选有界队列。

PriorityBlockingQueue :一个由优先级堆支持的无界优先级队列。

DelayQueue :一个由优先级堆支持的、基于时间的调度队列。

SynchronousQueue :一个利用 BlockingQueue 接口的简单聚集( rendezvous )机制

23/4/20Institute of Computer Software

Nanjing University

43

Page 44: Concurrent Programming in Java

实例 6: TestDelayQueue

23/4/20Institute of Computer Software

Nanjing University

44

Page 45: Concurrent Programming in Java

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

Page 46: Concurrent Programming in Java

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

Page 47: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

47

Page 48: Concurrent Programming in Java

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

Page 49: Concurrent Programming in Java

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

Page 50: Concurrent Programming in Java

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

Page 51: Concurrent Programming in Java

实例 7: TestCopyOnWrite

23/4/20Institute of Computer Software

Nanjing University

51

Page 52: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

52

Page 53: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

53

Page 54: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

54

Page 55: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

55

Page 56: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

56

Page 57: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

57

Page 58: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

58

Page 59: Concurrent Programming in Java

实例 8: ConditionTester

23/4/20Institute of Computer Software

Nanjing University

59

Page 60: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

60

Page 61: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

61

Page 62: Concurrent Programming in Java

实例 9: TestCyclicBarrier

23/4/20Institute of Computer Software

Nanjing University

62

Page 63: Concurrent Programming in Java

实例 10: TestCountDownLatch

23/4/20Institute of Computer Software

Nanjing University

63

Page 64: Concurrent Programming in Java

实例 11: TestSemaphore

23/4/20Institute of Computer Software

Nanjing University

64

Page 65: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

65

Page 66: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

66

Page 67: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

67

Page 68: Concurrent Programming in Java

23/4/20Institute of Computer Software

Nanjing University

68

Page 69: Concurrent Programming in Java

作业(本次作业不用提交)学习、研究 Doug Lea 的

java.util.concurrent 工具包的实现。尝试用这个工具包解决哲学家用餐问题。

23/4/20Institute of Computer Software

Nanjing University

69