1 / 69

Concurrent Programming in Java

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

Télécharger la présentation

Concurrent Programming in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Concurrent Programming in Java Java并发编程 Institute of Computer Software Nanjing University

  2. 摘要 • Java 1.5 并发工具包介绍 • 实例 Institute of Computer Software Nanjing University

  3. Java 并发编程机制 • Pre Java 1.5 • Thread, Runnable • synchronized • wait, notify, notifyAll Institute of Computer Software Nanjing University

  4. 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. Institute of Computer Software Nanjing University

  5. Java 并发编程机制 • Java 1.5+ Concurrent Utilities • Why? • What's new? • How to use? Let’s “listen to” some famous speech! Institute of Computer Software Nanjing University

  6. Institute of Computer Software Nanjing University

  7. Institute of Computer Software Nanjing University

  8. Institute of Computer Software Nanjing University

  9. Institute of Computer Software Nanjing University

  10. Institute of Computer Software Nanjing University

  11. Institute of Computer Software Nanjing University

  12. Institute of Computer Software Nanjing University

  13. Institute of Computer Software Nanjing University

  14. 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. Institute of Computer Software Nanjing University

  15. 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 Institute of Computer Software Nanjing University

  16. 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. Institute of Computer Software Nanjing University

  17. No need to write your own • java.util.concurrent.* • Executor framework • Executor框架组件提供了一个简单的、标准的、可扩充的类。该框架组件使调用、调度和执行的操作标准化了。它通过一组执行策略为控制异步事务提供了支持。 • Executor接口执行已提交的可以运行的事务。它提供了一条途径,允许我们把事务提交从事务执行机制中分离出来。程序员通常使用Executor代替显式地(explicitly)建立线程。Executor接口也提供事务的同步和异步执行。 Institute of Computer Software Nanjing University

  18. Institute of Computer Software Nanjing University

  19. 使用Executor接口 • public interface Executor • 执行已提交的 Runnable 任务的对象。此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节、调度等)分离开来的方法。通常使用 Executor 而不是显式地创建线程。例如: Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); Institute of Computer Software Nanjing University

  20. 实现Executor接口:立即执行 Class DirectExecutor implements Executor{ public void execute(Runnable r) { r.run(); } } Institute of Computer Software Nanjing University

  21. 实现Executor接口:异步执行 Class ThreadPerTaskExecutor implements Executor{ public void execute(Runnable r){ new Thread(r).start(); } } Institute of Computer Software Nanjing University

  22. 管理一个或多个异步事务的终止和跟踪事务执行的过程管理一个或多个异步事务的终止和跟踪事务执行的过程 Institute of Computer Software Nanjing University

  23. Institute of Computer Software Nanjing University

  24. Institute of Computer Software Nanjing University

  25. Institute of Computer Software Nanjing University

  26. 实例1: TestThreadPool Institute of Computer Software Nanjing University

  27. Notes • 合理选择 • 固定大小:Executors.newFixedThreadPool(int) • 单个后台:Executors.newSingleThreadPool() • 可延迟/定期执行:Executors.newScheduledThreadPool(int) • 手动配置:new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) • … Institute of Computer Software Nanjing University

  28. Notes • 必须显式地关闭 • 线程池必须使用shutdown来显式关闭,否则主线程就无法退出。shutdown也不会阻塞主线程。 Institute of Computer Software Nanjing University

  29. Institute of Computer Software Nanjing University

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

  31. 实例2: TestScheduledThread Institute of Computer Software Nanjing University

  32. Notes • 如何得到scheduler? final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); • 使用 • schedule, scheduleAtFixedRate, scheduleWithFixedDelay • 同样需要显示关闭 • scheduler.shutdown() • 但对于24小时运行的应用,无须关闭scheduler Institute of Computer Software Nanjing University

  33. Institute of Computer Software Nanjing University

  34. Future • public interface Future<V> • Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。 • get()方法:如有必要,等待计算完成,然后检索其结果(如果数据没有加载,就会阻塞直到取到数据 ) • get(long timeout, TimeUnit unit) • cancel(boolean)方法:试图取消对此任务的执行 Institute of Computer Software Nanjing University

  35. FutureTask • public class FutureTask<V> extends Object implements Future<V>, Runnable • 可取消的异步计算。利用开始和取消计算的方法、查询计算是否完成的方法和检索计算结果的方法,此类提供了对 Future 的基本实现。仅在计算完成时才能检索结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。 Institute of Computer Software Nanjing University

  36. 实例3: TestFutureTask Institute of Computer Software Nanjing University

  37. 实例4: TestCompletionService Institute of Computer Software Nanjing University

  38. Institute of Computer Software Nanjing University

  39. Institute of Computer Software Nanjing University

  40. Institute of Computer Software Nanjing University

  41. Institute of Computer Software Nanjing University

  42. 实例5: TestBlockingQueue Institute of Computer Software Nanjing University

  43. Notes • ArrayBlockingQueue :一个由数组支持的有界队列。 • LinkedBlockingQueue :一个由链接节点支持的可选有界队列。 • PriorityBlockingQueue :一个由优先级堆支持的无界优先级队列。 • DelayQueue :一个由优先级堆支持的、基于时间的调度队列。 • SynchronousQueue :一个利用 BlockingQueue 接口的简单聚集(rendezvous)机制 Institute of Computer Software Nanjing University

  44. 实例6: TestDelayQueue Institute of Computer Software Nanjing University

  45. 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. Institute of Computer Software Nanjing University

  46. 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. Institute of Computer Software Nanjing University

  47. Institute of Computer Software Nanjing University

  48. ConcurrentHashMap • putIfAbsent():只有在 map 不包含这个键时,才能将键加入到 map 中。如果 map 已经包含这个键,那么这个键的现有值就会保留。 putIfAbsent() 方法是原子的。 • 等价的 putIfAbsent() 代码if (!map.containsKey(key)) { return map.put(key, value); } else { return map.get(key); } Institute of Computer Software Nanjing University

  49. ConcurrentHashMap • remove():只有当键映射到指定的值时才从 map 中删除这个键。如果不匹配,那么就不删除这个键,并返回 false。如果值匹配键的当前映射内容,那么就删除这个键。 • 等价的 remove() 代码if (map.get(key).equals(value)){ map.remove(key); return true; } else { return false; } Institute of Computer Software Nanjing University

  50. 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. Institute of Computer Software Nanjing University

More Related