This document provides a summary of key chapters and concepts from the book "Java Concurrency in Practice" by Deon Huang. It discusses concurrency problems like race conditions, deadlocks, and starvation. Solutions covered include immutable objects, locks, synchronized collections, concurrent collections like ConcurrentHashMap, and building blocks like blocking queues, semaphores, and latches. It also reviews strategies for designing thread-safe classes through techniques like instance confinement and documenting synchronization policies. Advanced topics discussed include explicit locks, custom synchronizers, and the Java memory model.
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
processes, threads, how to define a thread, how to start a thread, how to sleep a thread, thread interrupt, interrupt status flag, joins, simple thread example, synchronization part 1, thread interference, memory consistency errors
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
synchronisation part 2, synchronized methods, intrinsic locks, atomic access, liveness, deadlock, starvation, livelock, guarded blocks, immutable objects, synchronized class example, strategy for defining immutable objects
Every Java developer knows that multithreading is the root of all evil and it is quite hard to write correct code for concurrent environment. But what tasks do exist in real commercial development except running code in asynchronous way?
In this talk I will present several tasks from my real projects and solutions we designed for them. This talk is very application oriented and allows participants to extend their vision of concurrent programming.
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingSachintha Gunasena
This session discusses a basic high-level introduction to concurrency programming with Java which include:
programming basics, OOP concepts, concurrency, concurrent programming, parallel computing, concurrent vs parallel, why concurrency, real world example, terms, Moore's Law, Amdahl's Law, types of parallel computation, MIMD Variants, shared memory model, distributed memory model, client server model, scoop mechanism, scoop preview - a sequential program, in a concurrent setting - using scoop, programming then & now, sequential programming, concurrent programming,
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
processes, threads, how to define a thread, how to start a thread, how to sleep a thread, thread interrupt, interrupt status flag, joins, simple thread example, synchronization part 1, thread interference, memory consistency errors
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
synchronisation part 2, synchronized methods, intrinsic locks, atomic access, liveness, deadlock, starvation, livelock, guarded blocks, immutable objects, synchronized class example, strategy for defining immutable objects
Every Java developer knows that multithreading is the root of all evil and it is quite hard to write correct code for concurrent environment. But what tasks do exist in real commercial development except running code in asynchronous way?
In this talk I will present several tasks from my real projects and solutions we designed for them. This talk is very application oriented and allows participants to extend their vision of concurrent programming.
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingSachintha Gunasena
This session discusses a basic high-level introduction to concurrency programming with Java which include:
programming basics, OOP concepts, concurrency, concurrent programming, parallel computing, concurrent vs parallel, why concurrency, real world example, terms, Moore's Law, Amdahl's Law, types of parallel computation, MIMD Variants, shared memory model, distributed memory model, client server model, scoop mechanism, scoop preview - a sequential program, in a concurrent setting - using scoop, programming then & now, sequential programming, concurrent programming,
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...Anand Narayanan
■ With the advent of multi-core processors the usage of single threaded programs is soon becoming obsolete. Java was built to be able to do many things at once. In computer lingo, we call this "concurrency". This is the main reason why Java is so useful. Today we see a lot of our applications running on multiple cores, concurrent java programs with multiple threads is the answer for effective performance and stability on multi-core based applications. Concurrency is among the utmost worries for newcomers to Java programming but there's no reason to let it deter you. Not only is excellent documentation available but also pictorial representations of each topic to make understanding much graceful and enhanced. Java threads have become easier to work with as the Java platform has evolved. In order to learn how to do multithreaded programming in Java , you need some building blocks. Our training expert with his rich training and consulting experience illustrates with real application based case studies.
A set of slides on the basics of concurrency touching upon Java's support for multi-threaded programming, do's and dont's, common approaches to developing concurrent applications and evolution of APIs in Java that support effective multi-threaded programming
Threads And Synchronization in C#
Concept about Threads And Synchronization in C#
it will help you about this concept
feel free
Download free programming applications on
http://www.androidapplications.xyz
Slide deck from my presentation on multi-threading with .NET. The presentation covers from beginner onwards and looks at current technologies (i.e. pre .NET 4.0) specifically.
What makes this extra special is the entire process of how I prepared for it, from finding content to slide deck layout to presentation prep is documented at: http://www.sadev.co.za/content/how-i-build-presentations-series-index
This slides is about SMP internals for Dalvik.Monitor is a synchronization construct that allows threads to have both mutux and the ability to wait for a certain condition to become true in Dalvik.
The latest source code of demos could be got from https://github.com/tek-life/Understanding_Monitor_for_Dalvik.
If there is something inappropriate in slides or demos, please let me know.
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
high-level concurrency objects, lock objects, executors, executor interfaces, thread pools, fork/join, concurrent collections, atomic variables, concurrent random numbers.
Threads are lightweight processes as the overhead of switching between threads is less
Synchronization allows only one thread to perform an operation on a object at a time.
Synchronization prevent data corruption
Thread Synchronization-The synchronized methods define critical sections.
You will learn the Deadlock Condition in Threads and Syncronization of Threads
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples and demos for all cases discussed will be added to my blog www.javajee.com.
In computer science, synchronization refers to one of two distinct but related concepts: synchronization of processes, and synchronization of data. Process synchronization refers to the idea that multiple processes are to join up or handshake at a certain point, in order to reach an agreement or commit to a certain sequence of action. Data synchronization refers to the idea of keeping multiple copies of a dataset in coherence with one another, or to maintain data integrity. Process synchronization primitives are commonly used to implement data synchronization.
Java Concurrency and Performance | Multi Threading | Concurrency | Java Conc...Anand Narayanan
■ With the advent of multi-core processors the usage of single threaded programs is soon becoming obsolete. Java was built to be able to do many things at once. In computer lingo, we call this "concurrency". This is the main reason why Java is so useful. Today we see a lot of our applications running on multiple cores, concurrent java programs with multiple threads is the answer for effective performance and stability on multi-core based applications. Concurrency is among the utmost worries for newcomers to Java programming but there's no reason to let it deter you. Not only is excellent documentation available but also pictorial representations of each topic to make understanding much graceful and enhanced. Java threads have become easier to work with as the Java platform has evolved. In order to learn how to do multithreaded programming in Java , you need some building blocks. Our training expert with his rich training and consulting experience illustrates with real application based case studies.
A set of slides on the basics of concurrency touching upon Java's support for multi-threaded programming, do's and dont's, common approaches to developing concurrent applications and evolution of APIs in Java that support effective multi-threaded programming
Threads And Synchronization in C#
Concept about Threads And Synchronization in C#
it will help you about this concept
feel free
Download free programming applications on
http://www.androidapplications.xyz
Slide deck from my presentation on multi-threading with .NET. The presentation covers from beginner onwards and looks at current technologies (i.e. pre .NET 4.0) specifically.
What makes this extra special is the entire process of how I prepared for it, from finding content to slide deck layout to presentation prep is documented at: http://www.sadev.co.za/content/how-i-build-presentations-series-index
This slides is about SMP internals for Dalvik.Monitor is a synchronization construct that allows threads to have both mutux and the ability to wait for a certain condition to become true in Dalvik.
The latest source code of demos could be got from https://github.com/tek-life/Understanding_Monitor_for_Dalvik.
If there is something inappropriate in slides or demos, please let me know.
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
high-level concurrency objects, lock objects, executors, executor interfaces, thread pools, fork/join, concurrent collections, atomic variables, concurrent random numbers.
Threads are lightweight processes as the overhead of switching between threads is less
Synchronization allows only one thread to perform an operation on a object at a time.
Synchronization prevent data corruption
Thread Synchronization-The synchronized methods define critical sections.
You will learn the Deadlock Condition in Threads and Syncronization of Threads
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples and demos for all cases discussed will be added to my blog www.javajee.com.
In computer science, synchronization refers to one of two distinct but related concepts: synchronization of processes, and synchronization of data. Process synchronization refers to the idea that multiple processes are to join up or handshake at a certain point, in order to reach an agreement or commit to a certain sequence of action. Data synchronization refers to the idea of keeping multiple copies of a dataset in coherence with one another, or to maintain data integrity. Process synchronization primitives are commonly used to implement data synchronization.
Thread vs Process
scheduling
synchronization
The thread begins execution with the C/C run-time library startup code.
The startup code calls your main or WinMain and execution continues until the main function returns and the C/C library code calls ExitProcess.
Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. The classes that give access to the metadata of a running program are in System.Reflection.
System.Reflection namespace defines the following types to analyze the module's metadata of an assembly:
Assembly, Module, Enum, ParameterInfo, MemberInfo, Type, MethodInfo, ConstructorInfo, FieldInfo, EventInfo, and PropertyInfo
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
4. Overview
• What is concurrency problem?
• Why does it important?
• What is thread and process?
• What is thread safety?
• What is the outcome of the book?
5. Where does concurrency problem
come from?
• This is a breakfast shop
• Suppose you are the only cook.
• Only waiter
• Only dish washer
• It’s lunch time
• And you gave 3 client at same time
Need more workers (Multithreading)
6. What is concurrency problem?
• Now you get many cooks
• What happen when you order
• One steamed port dumplings?
• The answer is no one knows!
8. What is the outcome of the book?
• 1.Introduction
• I Fundamentals
• 2.Thread Safety
• 3.Sharing Objects
• 4.Composing Objects
• 5.Building Blocks
• II Structuring Concurrent Applications
• 6.Task Executing
• 7.Cancellation and Shutdown
• 8.Applying Thread Pools
• 9.GUI Applications
• III Liveness, Performance, and Testing
• 10.Avoiding Liveness Hazards
• 11.Performance and Scalability
• 12.Testing Concurrent Programs
• IV Advanced Topics
• 13.Explicit Locks
• 14.Building Custom Synchronizers
• 15.Atomic Variables and Nonblocking Synchronization
• 16.The Java Memory Model
9. Chapter 1 Introduction Goal
• Understand what kind problem this book is trying to solve
• Why it’s important?
• What is thread?
Background knowledge preparation (Multithreading)
10. Chapter 1 Introduction
• Coarse grained communication mechanisms of processes : Sockets,
signal handler, shared memory, semaphore, files.
• Sequential programming model.
• Threads provide multiple control flow to coexist within a process
• Threads share process resources such as memory, file handler, but
each has program counter, stack and variables.
11. 1.2 Benefit of Thread
• Exploiting multiple processor
• Simplicity of task modeling
• Simplified handling of Asynchronous events
• More responsive user interface
• Programming abstraction
• Parallelism
• Blocking I/O
• Memory savings
12. 1.2 Benefit of Thread
• How to sell soufflé?
• Program : recipe and plan
• Process : bread store
• Thread : bakers
13. 1.2 Benefit of Thread
Process Thread
Concept Instance that execute
program
Minimum unit of execution
Consists of Memory space
Threads
program counter, a stack, and a
set of registers, ( and a thread
ID. )
Communication Inter process
communication
Directly communicate
Memory Separate memory space Shared memory space
Controlled by Operating system Programmer in program
14. 1.3 Risk of thread
• Safety Hazards : race condition
• Output is dependent on the sequence or timing of other
uncontrollable events.
15. 1.3 Risk of thread
• Safety Hazards : race condition
• Output is dependent on the sequence or timing of other
uncontrollable events.
A
B
16. 1.3 Risk of thread
• Liveness Hazards :
an activity gets into a state such that it is permanently unable t
o make forward progress.
• Deadlock
• Starvation
• Livelock
17. 1.3 Risk of thread
• Performance Hazards :
poor service time, responsiveness, throughput, resource consum
ption, or scalability.
• Context switches : when the scheduler suspends the active thre
ad temporarily so another thread can run are more frequent in
applications with many threads, and have significant costs:
saving and restoring execution context, loss of locality and CPU spent
scheduling thread instead of running them.
18. 1.4 Threads Are Everywhere
• Key point : thread-safe
• Examples in Java:
• RMI
• JSP
• Servlet
• Timer
• Swing and AWT (GUI application)
19. Chapter 1 Introduction Review
• Understand what kind problem this book is trying to solve
• Concurrency issue
• Why it’s important?
• Utilize thread for better performance
• What is thread?
• Smallest unit of worker in process
20.
21. Chapter 2 Thread Safety Goal
• What is thread safety?
• How to achieve it?
• Meet Atomicity
• Meet Lock
• Thread safety awareness
22. Chapter 2 Thread Safety
• A class is thread-safe if it behaves correctly when accessed from
multiple threads.
23. 2.1 Thread-safe
• Basically key point is manage access to state
• Don't share the state variable across threads;
• Make the state variable immutable; or
• Use synchronization whenever accessing the state variable.
• Stateless object is always thread-safe
25. 2.2 Atomicity
• Race condition can cause problem in lazy-initialization and state
modification.
• Atomic operation is one that is atomic with respect all operations
which on the same state, either executed or none of it has.
• Compound action to gain atomicity.
• To preserve state consistency, update related state variables in a
single atomic operation.
27. 2.3.1 Intrinsic Locks
• Java provide a built-in locking mechanism for enforcing atomicity:
the synchronized block.
• Synchronized block has two parts: a reference to an object that serve
as the lock, and a block of code guarded by that lock.
• Every Java object can implicitly act as a lock for purposes of
synchronization.
31. 2.4 Guarding State with locks
• For each mutable state variable that may be accessed by more than
one thread, all accesses to that variable must be performed with the
same lock held.
• Every shared, mutable variable should be guarded by exactly one
lock.
36. 2.3.5 Liveness and Performance
• Simplicity versus performance
• Avoid holding locks during lengthy computations like network or
console I/O.
37. Chapter 2 Thread Safety Review
• What is thread safety?
• Behaves correctly when accessed from multiple threads.
• How to achieve it?
• Manage access to state
• Meet Atomicity
• Actions and sets of actions have indivisible effects
• Meet Lock
• A tool for controlling access to a shared resource by multiple threads
• Thread safety awareness
• Simplicity versus performance
39. Concurrency Problem
Common problem Description
Safety Hazards Race Condition, Atomicity, Visibility, Ordering
Liveness Hazards DeadLock, Starvation, LiveLock,
Performance Hazards Spin wait, responsiveness, throughput, Amdahl's Law, Gustafson’s Law.
Lock Contention
Starvation perpetually denied access to resources
DeadLock Lock ordering deadlock
LiveLock not blocked, still cannot make progress
40. Concurrency Solution
Common Solution Description
Immutable Uneditable as stateless object for thread safety
Lock Guarantee critical zone by holding lock
Synchronized Collection Thread-safety but one thread can access at same time
Concurrent Collection Thread-safety with lock striping for better performance and concurrency
Future Asynchronized computing result
Thread Confinement Object is confined to a thread like ThreadLocal
Volatile Light synchronized mechanism that only provide Visibility
CAS Optimistic techniqueit proceeds with the update in the hope of success
41. Concurrency Skill
Common Solution Description
Intrinsic Lock Every object has a built-in lock
Read Write Lock Locking strategy that prevents writer/reader overlap
Semaphores Control the number access at the same time
Latch Gate that waiting for an event to release
Barrier Gate that waiting for an object to release
Happen Before Thread relationship to ensure Ordering
42. FAQ
• Multithreading: What is the point of more threads than cores?
• Thread vs Process?
• What does threads consist of?
• What does threads share?
• Data Segment(global variables,static data)
• Address space.
• Code Segment.
• I/O, if file is open , all threads can read/write to it.
• Process id of parent.
• The Heap
• What is a dead lock, starvation, race condition, livelock?
• What is volatile variables
43. Advanced Topic
• 1.Introduction
• I Fundamentals
• 2.Thread Safety
• 3.Sharing Objects
• 4.Composing Objects
• 5.Building Blocks
• II Structuring Concurrent Applications
• 6.Task Executing
• 7.Cancellation and Shutdown
• 8.Applying Thread Pools
• 9.GUI Applications
• III Liveness, Performance, and Testing
• 10.Avoiding Liveness Hazards
• 11.Performance and Scalability
• 12.Testing Concurrent Programs
• IV Advanced Topics
• 13.Explicit Locks
• 14.Building Custom Synchronizers
• 15.Atomic Variables and Nonblocking Synchronization
• 16.The Java Memory Model
44. Conclusion
• Concept of concurrency problem
• Meet Java Concurrency in Practice
• Meet concurrency problem and solution
• Meet FAQ
49. 3.1 Visibility
• Reordering : compiler or processor somehow will reorder instruction
for some optimization. So, never assume memory actions must
happen in insufficiently synchronized multithreaded programs.
• Locking can guarantee both visibility and atomicity.
51. 3.1.4 Volatile Variables
• Background :
Synchronized has relatively large overhead.
Sometimes we want lighter synchronization.
• s
52. 3.1.4 Volatile Variables
• Implementation :
When a field is declared volatile, the compiler
and runtime are put on notice that this variable is shared and that o
perations on it should not be reordered with other memory operatio
ns
• Volatile variables are not cached in registers or in caches where they
are hidden from other processors, so a read of a volatile variable always
returns the most recent write by any thread.
• Yet accessing a volatile variable performs no locking and so cannot
cause the executing thread to block, making volatile variables a
lighter weight synchronization mechanism than synchronized
56. 3.2 Publication and Escape
• Inner class has hidden enclosing instance reference, so never publish
at constructor
57. 3.2 Publication and Escape
• Skills: do not let this escape during constructor
• In practical : launch thread later with start method.
58. 3.3 Thread Confinement
• If data is only accessed from a single thread, no synchronization is
needed.
• There are existing ThreadLocal class but even with these, it is still the
programmer's responsibility to ensure that thread confined objects
do not escape from their intended thread.
• Good example is combine Thread confinement concept with Volatile
variables, this make sure only one thread write and gain visibility from
Volatile.
60. 3.3 Thread Confinement
• A more formal means of maintaining thread confinement is
ThreadLocal, which allows you to associate a per thread value with
a value holding object
61. 3.4 Immutability
• An immutable object is one whose state cannot be changed after
construction
• The final keyword, a more limited version of the const mechanism
from C++
66. Chapter 4 Composing Object
• This chapter covers patterns for structuring classes that
can make it easier to make them thread
safe and to maintain them without accidentally undermining their
safety guarantees.
•
69. 4.1 Designing a thread safe class
• Gathering Synchronization Requirements :
• State dependent Operations :
• The built in mechanisms for efficiently waiting for a condition to become
true wait and notify are tightly bound to intrinsic locking, and can be difficult
to use correctly
• such as blocking queues or semaphores, to provide the desired state
dependent behavior. Blocking library classes such as BlockingQueue, Semapho
re
•
70. 4.2. Instance Confinement
• Gathering Synchronization Requirements :
• State dependent Operations :
• The built in mechanisms for efficiently waiting for a condition to become
true wait and notify are tightly bound to intrinsic locking, and can be difficult
to use correctly
• such as blocking queues or semaphores, to provide the desired state
dependent behavior. Blocking library classes such as BlockingQueue, Semapho
re
•
74. 4.2. Instance Confinement
• To make this approach work, we have to use the same lock that the
List uses by using client-side locking or external
• locking.
• s
75. 4.2. Instance Confinement
• To make this approach work, we have to use the same lock that the
List uses by using client-side locking or external
• locking.
• s
76. 4.2. Instance Confinement
• To make this approach work, we have to use the same lock that the
List uses by using client-side locking or external locking.
• s
78. Chapter 4 Review
• To make this approach work, we have to use the same lock that the
List uses by using client-side locking or external locking.
• s
79. Chapter 5 Building Block
• This chapter covers the most useful concurrent building blocks, e
specially those introduced in Java 5.0 and Java 6, and some patt
erns for using them to structure concurrent applications.
80. 5.1 Synchronization Collection
• Synchronization collection is not suitable for compound actions
• Common compound actions on collections include
• iteration (repeatedly fetch elements until the collection is exhausted),
• navigation (find the next element after this one according to some order)
• conditional operations such as put if absent
(check if a Map has a mapping for key K, and if not, add the mapping).=
85. 5.2 Concurrent collection
• This chapter covers the most useful concurrent building blocks, e
specially those introduced in Java 5.0 and Java 6, and some patt
erns for using them to structure concurrent applications.
86. Chapter 5 Building Block
• ConcurrentHashMap, a replacement for synchronized hash based Map
implementations, and CopyOnWriteArrayList, a replacement for
synchronized List implementations
• Java 5.0 also adds two new collection types, Queue and BlockingQueue.
• BlockingQueue extends Queue to add blocking insertion and retrieval
operations.
• blocking queues are extremely useful in producer consumer designs
87. 5.2.1. ConcurrentHashMap
• Instead of synchronizing every method on a common lock, restricting
access to a single thread at a time, it uses a finer grained locking
mechanism called lock striping
Item SynchronizedHashMap ConcurrentHashMap
Client-side lock Lock striping
Intrinsic Lock Higher throughput
Better scalibility
Null key, value Allow Not allow
f empty(), size() result is
approximation
Iterator Fail fast Weak consistent
89. 5.3. Blocking Queues and the Producer
consumer Pattern
• Blocking queues also provide an offer method, which returns a failure
status if the item cannot be enqueued
90. 5.3.3. Deques and Work Stealing
• Java 6 also adds another two collection types, Deque (pronounced
"deck")
• A Deque is a double ended queue that allows efficient insertion and
removal from both the head and the tail. Implementations include
ArrayDeque and LinkedBlockingDeque.
• Just as blocking queues lend themselves to the producer
consumer pattern, deques lend themselves to a related pattern
called work stealing.
91. 5.4. Blocking and Interruptible Methods
• When a thread blocks, it is usually suspended and placed in one of
the blocked thread states (BLOCKED, WAITING, or TIMED_WAITING).
• When a method can throw InterruptedException, it is telling you
that it is a blocking method, and further that if it is interrupted, it
will make an effort to stop blocking early.
93. 5.5. Synchronizers
• A synchronizer is any object that coordinates the control flow of
threads based on its state.
• Blocking queues can act as synchronizers; other types of
synchronizers include semaphores, barriers, and latches.
• All synchronizers share certain structural properties:
• they encapsulate state that determines whether threads arriving at the
synchronizer should be allowed to pass or forced to wait,
• provide methods to manipulate that state, and
• provide methods to wait efficiently for the synchronizer to enter the desired
state.
94. 5.5.1 Latches
• Synchronizer that can delay threads until it reaches its terminal state
• 1-Ensuring that a computation does not proceed until resources it
needs have been initialized.
• 2-Ensuring that a service does not start until other services on which it depends
have started
• 3-Waiting until all the parties involved in an activity
• Ex: CountdownLatch
95. 5.5.2 FutureTask
• FutureTask also acts like a latch. A computation represented by a
FutureTask is implemented with a Callable
• the result bearing equivalent of Runnable, and can be in one of
three states: waiting to run, running, or completed.
• The behavior of Future.get depends on the state of the task.
96. 5.5.3. Semaphores
• Counting semaphores are used to control the number of activities
that can access a certain resource or perform a given action at the
same time [CPJ 3.4.1].
• Counting semaphores can be used to implement resource pools or to
impose a bound on a collection.
97. 5.5.4. Barriers
• Barriers are similar to latches in that they block a group of threads
until some event has occurred [CPJ 4.4.3].
• The key difference is that with a barrier, all the threads must come
together at a barrier point at the same time in order to proceed.
• Threads call await when they reach the barrier point, and await
blocks until all the threads have reached the barrier point.
• If all threads meet at the barrier point, the barrier has been
successfully passed, in which case all threads are released and the
barrier is reset so it can be used again.