Working With Concurrency In Java 8

26
WORKING WITH CONCURRENCY IN JAVA 8 Designing & developing concurrent applications using Java 8 . Presenter: Heartin Jacob Kanikathottu

Transcript of Working With Concurrency In Java 8

Page 1: Working With Concurrency In Java 8

WORKING WITH CONCURRENCY IN JAVA 8

Designing & developing concurrent applications using Java 8.

Presenter: Heartin Jacob Kanikathottu

Page 2: Working With Concurrency In Java 8

DISCLAIMER!

Aim of this presentation is not to make you masters in Java 8 Concurrency, but to helpyou guide towards that goal. Sometimes it helps just to know that there is some API thatmight be suitable for a particular situation. Make use of the pointers given to searchmore and learn more on those topics. Refer to books, Java API Documentation, Blogsetc. to learn more. Examples for all cases discussed will be added to my blogwww.javajee.com. I usually stress on few slides and run through few others, based onthe type of audience I am presenting. Fresher's or new developers might find the initialslides more interesting whereas experienced Java developers may like the latter slidesmore. Please check the references section for the books and resources I have referredfor preparing this. Please contact me for any queries or clarifications.

Page 3: Working With Concurrency In Java 8

TOPICS

• Basic Java Concurrency Concepts

• Fork / Join Framework

• Concurrency in Java 8, with tips and tricks

• Steps to design concurrent applications

• Additional Tips and Tricks

• Demos

• Resources

Page 4: Working With Concurrency In Java 8

PART 1 – BASIC JAVA CONCURRENCY CONCEPTS

• Quick Intro to Java Concurrency API

• Quick Look into Basic Concurrency Concepts

• Why concurrency?

• Synchronization mechanisms

• Thread safety

• Synchronization problems

• Concurrency Design Principles

Page 5: Working With Concurrency In Java 8

QUICK INTRO TO CONCURRENCY API

• Improved always through different versions of Java

• Thread, Runnable from Java 1.0, ThreadLocal from 1.2.

• Java 5 had introduced the Executor framework.

• Java 6 had minimal changes related to concurrency

• Java 7 introduced the Fork/Join framework and the Phaser.

• Java 8 has introduced Stream API along with many other classes.

• Concurrency API also includes many concurrent data structures and synchronous mechanisms.

Page 6: Working With Concurrency In Java 8

BASIC CONCURRENCY CONCEPTS

• Improve performance utilizing all the cores.

• Synchronization

• Semaphore to controlling access to a common resource.

• Monitor to get mutual exclusion over a shared resource.

• Thread safety

• Immutable objects to get thread safety without explicit synchronization.

• Atomic variables with atomic operations.

• Synchronization problems• Race condition, Deadlock, Livelock, Resource Starvation, Priority Inversion.

Page 7: Working With Concurrency In Java 8

CONCURRENCY DESIGN PRINCIPLES

• Signaling• Notify event to another task.

• Rendezvous –• Generalization of Signaling: Notify each other

• Mutex• Critical section ensuring mutual exclusion.

• Multiplex –• Generalization of Mutex: Determined number can execute the critical section.

• Can be implemented using Semaphore.

Page 8: Working With Concurrency In Java 8

CONCURRENCY DESIGN PRINCIPLES (COND..)

• Barrier• Synchronize tasks at a common point.

• CyclicBarrier implement this pattern.

• Read-write lock• Write happen alone, read can happen in parallel.

• Implemented by ReentrantReadWriteLock

• Double check locking

• Thread pool

• Thread local storage.

Page 9: Working With Concurrency In Java 8

PART 2 - FORK/JOIN FRAMEWORK

• Intro to Fork /Join Framework

• Fork / Join Framework components

• Fork / join Methods

• Limitations of Fork / Join Framework

Page 10: Working With Concurrency In Java 8

INTRO TO FORK / JOIN FRAMEWORK

• Special kind of Executor

• For divide and conquer solutions

• Uses work stealing algorithm

• Tasks attempt to find (steal) tasks submitted b other tasks

• Avoid threads waiting for work

• Used by many implementations internally in Java 8, such as parallelSort() or arrays, parallel streams and even concurrent hash map.

Page 11: Working With Concurrency In Java 8

FORK / JOIN COMPONENTS

• ForkJoinPool class

• Special executor with work stealing algorithm

• Java 8 includes a default ForkJoinPool called common pool.

• ForkJoinTask

• Abstract base task for tasks that run within a ForkJoinPool

• Provides fork() and join() methods and few variants

• RecursiveTask - Sub class that should be starting point for tasks that return a result.

• RecursiveAction – Sub class that should be starting point for tasks that don’t return result.

• CountedCompleter – Starting point for tasks that trigger other tasks when they are completed.

Page 12: Working With Concurrency In Java 8

IMPORTANT FORK/JOIN METHODS

• Join vs quietlyJoin• Join throws exception

• Quietly join will ignore exceptions

• Execute vs. invoke vs. submit• Sends the task to ForkJoinPool

• Execute returns immediately a void value

• Invoke returns when the task has finished execution. Also have quetlyInvoke.

• Submit returns immediately a future object.

• Submit has also versions that accept Runnable and Callable.

Page 13: Working With Concurrency In Java 8

LIMITATIONS OF FORK / JOIN FRAMEWORK

• Problems could be solved using divide and conquer.

• Should not block on IO operations.

• Docn gives no work stealing guarantees in face of blocked IO or unmanaged synchronization

• Can’t throw checked exceptions

• Should wrap exceptions into unchecked exceptions and handle them.

Page 14: Working With Concurrency In Java 8

PART 3 - CONCURRENCY IN JAVA 8

• Important Concurrency Java 8 Additions

• Working with Parallel Streams

• Working with Atomic Variables

• Tips and Tricks for working with Concurrency APIs in Java 8

Page 15: Working With Concurrency In Java 8

IMPORTANT JAVA 8 CONCURRENCY ADDITIONS

• Stream API, Lambda expressions and Parallel streams

• Stamped Lock

• Parallel sort for arrays

• Default ForkJoinPool: Common pool.

• CountedCompleter

• CompletableFuture

• Double Added, LongAdder, DoubleAccumulator, LongAccumulator.

• New methods in Collection, ConcurrentMap and ConcurrentHashMap

Page 16: Working With Concurrency In Java 8

WORKING WITH PARALLEL STREAMS

• Stream() vs. parallelStream() in Collection interface

• Arrays do no have a parallelStream() method.

• Parallel() vs. sequential()

• Parallel streams internally uses fork/join framework

• Elements may be processed in any order in parallel streams

• Avoid using stateful operations or that based on order within parallel streams

• Operations that depend on previous state like a loop iteration that is based on previous.

• E.g. Sorted, findFirt.

Page 17: Working With Concurrency In Java 8

WORKING WITH ATOMIC VARIABLES

• DoubleAdder• preferable to alternatives when frequently updated but less frequently read

• LongAdder• under high contention, expected throughput of this class is significantly higher compared to

AtomicLong, at the expense of higher space consumption.

• DoubleAccumulator• preferable to alternatives when frequently updated but less frequently read

• LongAccumulator• under high contention, expected throughput of this class is significantly higher compared to

AtomicLong, at the expense of higher space consumption.

Page 18: Working With Concurrency In Java 8

TIPS AND TRICKS

• Identify correct independent tasks.

• Use most appropriate atomic class for the situation.

• Find easily parallelizable version of algorithm.

• Use right identity while using reduce() with parallel streams.

• Avoid using stateful operations within parallel streams.

• Intermediate operations are not executed until a terminal operation (for all streams)

• Collect might be more efficient that reduce in most cases (for all streams)

Page 19: Working With Concurrency In Java 8

TIPS AND TRICKS (COND..)

• Iterate() method of Stream interface should be avoided as much as possible.

• Most of the File class methods parallelize badly.

• SplittableRandom class is more suitable in parallel processing than Random class.

• Should use immutable objects as Identity object.• All threads share the identity object in case of parallel streams.

• Parallelism threshold parameter of Concurrency methods should be used wisely.

• E.g. search(), reduce(), compute etc. of ConcurrentHashMap

• Parallel streams are not always the faster ones.

Page 20: Working With Concurrency In Java 8

PART 4 – DESIGNING CONCURRENT APPLICATIONS

• Steps to design concurrent applications

• Additional tips and tricks

• Demo: Merge Sort Sequential and Parallel Versions.

• Demo: Additional Java 8 Parallel Streams methods.

Page 21: Working With Concurrency In Java 8

STEPS TO DESIGN CONCURRENT APPLICATIONS

• Look for: Efficiency, Simplicity, Portability, Scalability.

• Starting point:

• A sequential version of algorithm.

• Can verify for correctness.

• Can see if performance really improves.

• Step 1: Analysis –

• Find good candidates.

• E.g. Loops whose iteration does not depend on previous iterations.

Page 22: Working With Concurrency In Java 8

STEPS TO DESIGN CONCURRENT APPLICATIONS (COND..)

• Step 2: Design

• Task decomposition, Data decomposition

• Step 3: Implement

• Implement using a programming language.

• Step 4: Test

• Test and compare against sequential

• Step 5: Tuning

• Speedup, Amdahl’s law, Gustafson-Barsis’ Law.

Page 23: Working With Concurrency In Java 8

ADDITIONAL TIPS AND TRICKS

• Use higher level abstractions.

• Look for Scalability

• Use thread safe APIs when needed

• Never assume an execution order

• Avoid deadlocks by ordering locks

• Prefer local thread variables over static and shared

• Hold locks for as short time as possible

Page 24: Working With Concurrency In Java 8

ADDITIONAL TIPS AND TRICKS (CONTD..)

• Use immutable objects

• Use atomic variables instead of synchronization

• Avoid use of blocking operations within critical sections.

• Always refer to Java API Documentation when in doubt.

Page 25: Working With Concurrency In Java 8

RESOURCES & REFERENCES

• Java Concurrency in Practice• by Brian Goetz, Tim Peierls , Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea

• Mastering Concurrency Programming with Java 8• by Javier Fernandez Gonzalez

• www.JavaJee.com• For my personal notes and examples. Got to Java section and look for multithreading.

• Oracle Java API Documentation: Ultimate place to look for anything.

Page 26: Working With Concurrency In Java 8

WHAT NEXT?

• There is a lot more to learn.

• Continue learning together.

• Free after session support for continuous learning. J

• Contact me through www.javajee.com for any queries or doubts. Discuss any query through the Timeline section or the Forum section, or even the contact page.