We live in a world where parallel computing is becoming more and more ubiquitous: from large-scale GPU-based computing grids for bitcoin mining and montecarlo simulations, to 16+ cores desktop processors, 5760 shader cores GPUs, and octa-core smartphones.
Leveraging this computing power in an effective way while also guaranteeing correctness requires a deep understanding of the threading capabilities and of the memory model behaviors hidden behind the language primitives that we use every day while coding.
Yet, concurrency is one of the least taught subject in programming courses around the world, and one of the most obscure topic for the developers, often also very senior ones.
We'll explore the topic together by walking through cases in the Java world. We'll also delve into novel approaches that can simplify it, such as Actors and Software Transactional Memory.
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Codemotion
Per anni i threads sono stati il solo modello di concorrenza sulla JVM. Tuttavia usarli correttamente è difficile, e anche per questo altri modelli di concorrenza stanno guadagnando popolarità. Akka ha reso disponibile sulla JVM gli attori originalmente implementati in Erlang. Clojure ha separato una referenza dalla serie di valori che assume nel tempo introducendo il concetto di STM. Infine anche la programmazione funzionale sta giocando un ruolo importante nel semplificare le tecniche di parallelizzazione. Lo scopo del talk è comparare pro e contro di questi diversi modelli di concorrenza.
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Codemotion
Per anni i threads sono stati il solo modello di concorrenza sulla JVM. Tuttavia usarli correttamente è difficile, e anche per questo altri modelli di concorrenza stanno guadagnando popolarità. Akka ha reso disponibile sulla JVM gli attori originalmente implementati in Erlang. Clojure ha separato una referenza dalla serie di valori che assume nel tempo introducendo il concetto di STM. Infine anche la programmazione funzionale sta giocando un ruolo importante nel semplificare le tecniche di parallelizzazione. Lo scopo del talk è comparare pro e contro di questi diversi modelli di concorrenza.
Slides from my DevOpsExpo London talk "From oops to NoOps".
They tell you in these conferences that DevOps is not about tools, but about culture. And they are partially right. I am going to tell you that it’s not only about culture or tools but also abstractions.
It is a lot about how you see software and its value. About our mental model of what software is: how it runs, evolves, and interacts with the other facets of an enterprise.
We used to view software as code. As a state of code. Now we think about software as change, as a flow. A dynamic system where people, machines, and processes interact continuously.
At Platform.sh we spend a bunch of time asking ourselves not “How do you build?” - or even “How do you build consistently?” - but rather “What does it mean to consistently build in a world where change is good?” A world that lets you push security fixes into production as soon as they’re available because you don’t want to be an Equifax but you do want stability.
In this presentation, I will go over what we think software is and why having the right ideas about software will help you get your culture right and your tooling aligned, as well as gain in productivity, and general happiness and well-being.
A Java compiler is a compiler for the development terminology Java. The most frequent way of outcome from a Java compiler is Java category data files containing platform-neutral Java bytecode,
This Book helps the students who are persuing B.Sc Computer Science in Andhra Pradesh. It made for learning in easiest way. Words have used in this book are very familiar. Any one can understand the language easily. Prefer this book to learn Java.
Vibrant Technologies is headquarted in Mumbai,India.We are the best Java training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Java classes in Mumbai according to our students and corporators
Deep Learning libraries and first experiments with TheanoVincenzo Lomonaco
In recent years, neural networks and deep learning techniques have shown to perform well on many
problems in image recognition, speech recognition, natural language processing and many other tasks.
As a result, a large number of libraries, toolkits and frameworks came out in different languages and
with different purposes. In this report, firstly we take a look at these projects and secondly we choose the
framework that best suits our needs: Theano. Eventually, we implement a simple convolutional neural net
using this framework to test both its ease-of-use and efficiency.
Go Best Practices – Interfaces, Packages and APIsMarcus Kohlberg
Learn about designing interfaces, packages and APIs. Presentation by André Eriksson, founder of Encore. Originally presented at the Go naviro conference.
The course aims to provide you with an understanding of the fundamental concepts involved in object-oriented programming (object, class, protocol, hierarchy, inheritance, encapsulation, polymorphism and collaboration).
The programming language you will use is Java. However, the purpose of the course is not to teach you the minutiae of the Java language, but rather to teach you fundamental object-oriented programming concepts and skills that will be transferable to any object¬ oriented language
This presentation by Maksym Fastovets (Senior Software Engineer, Consultant, GlobalLogic, Kharkiv) was delivered at GlobalLogic Kharkiv Java Conference 2019 on June 9, 2019.
Maksym touched upon the Java development from Thread to CompletableFuture and introduced the Monitor concept and its implementation in Java. He also did not overlook Java tools supporting multithreading and asynchronous coding that exist aside from JDK.
Video: https://youtu.be/pLXQWbwneOw
The network as a design material: Interaction 16 workshopClaire Rowland
Exploring the UX challenges which the properties of networks and connectivity patterns pose to connected products/the internet of things: latency, reliability, intermittent connectivity
Reactive design: languages, and paradigmsDean Wampler
A talk first given at React 2014 and refined for YOW! LambdaJam 2014 that explores the meaning of Reactive Programming, as described in the Reactive Manifesto, and how well it is supported by general design paradigms, like Functional Programming, Object-Oriented Programming, and Domain Driven Design, and by particular design approaches, such as Functional Reactive Programming, Reactive Extensions, Actors, etc.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
More Related Content
Similar to Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
Slides from my DevOpsExpo London talk "From oops to NoOps".
They tell you in these conferences that DevOps is not about tools, but about culture. And they are partially right. I am going to tell you that it’s not only about culture or tools but also abstractions.
It is a lot about how you see software and its value. About our mental model of what software is: how it runs, evolves, and interacts with the other facets of an enterprise.
We used to view software as code. As a state of code. Now we think about software as change, as a flow. A dynamic system where people, machines, and processes interact continuously.
At Platform.sh we spend a bunch of time asking ourselves not “How do you build?” - or even “How do you build consistently?” - but rather “What does it mean to consistently build in a world where change is good?” A world that lets you push security fixes into production as soon as they’re available because you don’t want to be an Equifax but you do want stability.
In this presentation, I will go over what we think software is and why having the right ideas about software will help you get your culture right and your tooling aligned, as well as gain in productivity, and general happiness and well-being.
A Java compiler is a compiler for the development terminology Java. The most frequent way of outcome from a Java compiler is Java category data files containing platform-neutral Java bytecode,
This Book helps the students who are persuing B.Sc Computer Science in Andhra Pradesh. It made for learning in easiest way. Words have used in this book are very familiar. Any one can understand the language easily. Prefer this book to learn Java.
Vibrant Technologies is headquarted in Mumbai,India.We are the best Java training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Java classes in Mumbai according to our students and corporators
Deep Learning libraries and first experiments with TheanoVincenzo Lomonaco
In recent years, neural networks and deep learning techniques have shown to perform well on many
problems in image recognition, speech recognition, natural language processing and many other tasks.
As a result, a large number of libraries, toolkits and frameworks came out in different languages and
with different purposes. In this report, firstly we take a look at these projects and secondly we choose the
framework that best suits our needs: Theano. Eventually, we implement a simple convolutional neural net
using this framework to test both its ease-of-use and efficiency.
Go Best Practices – Interfaces, Packages and APIsMarcus Kohlberg
Learn about designing interfaces, packages and APIs. Presentation by André Eriksson, founder of Encore. Originally presented at the Go naviro conference.
The course aims to provide you with an understanding of the fundamental concepts involved in object-oriented programming (object, class, protocol, hierarchy, inheritance, encapsulation, polymorphism and collaboration).
The programming language you will use is Java. However, the purpose of the course is not to teach you the minutiae of the Java language, but rather to teach you fundamental object-oriented programming concepts and skills that will be transferable to any object¬ oriented language
This presentation by Maksym Fastovets (Senior Software Engineer, Consultant, GlobalLogic, Kharkiv) was delivered at GlobalLogic Kharkiv Java Conference 2019 on June 9, 2019.
Maksym touched upon the Java development from Thread to CompletableFuture and introduced the Monitor concept and its implementation in Java. He also did not overlook Java tools supporting multithreading and asynchronous coding that exist aside from JDK.
Video: https://youtu.be/pLXQWbwneOw
The network as a design material: Interaction 16 workshopClaire Rowland
Exploring the UX challenges which the properties of networks and connectivity patterns pose to connected products/the internet of things: latency, reliability, intermittent connectivity
Reactive design: languages, and paradigmsDean Wampler
A talk first given at React 2014 and refined for YOW! LambdaJam 2014 that explores the meaning of Reactive Programming, as described in the Reactive Manifesto, and how well it is supported by general design paradigms, like Functional Programming, Object-Oriented Programming, and Domain Driven Design, and by particular design approaches, such as Functional Reactive Programming, Reactive Extensions, Actors, etc.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Enhancing Performance with Globus and the Science DMZGlobus
ESnet has led the way in helping national facilities—and many other institutions in the research community—configure Science DMZs and troubleshoot network issues to maximize data transfer performance. In this talk we will present a summary of approaches and tips for getting the most out of your network infrastructure using Globus Connect Server.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Essentials of Automations: The Art of Triggers and Actions in FME
Thread with care: concurrency pitfalls in Java [Iași CodeCamp 25th October 2014]
1. Thread with care: concurrency pitfalls in Java
Luigi Lauro (Enteprise Architect - Product Line Group Risk Management)
UniCredit Business Integrated Solutions
Iași, 25 October 2014
2. Thread with care
Concurrency pitfalls in Java
We live in a world where parallel computing is becoming more and more
ubiquitous: from large-scale GPU-based computing grids for bitcoin mining and
montecarlo simulations, to 16+ cores desktop processors, 5760 shader cores
GPUs, and octa-core smartphones.
Leveraging this computing power in an effective way while also
guaranteeing correctness requires a deep understanding of the threading
capabilities and of the memory model behaviors hidden behind the language
primitives that we use every day while coding.
Yet, concurrency is one of the least taught subject in programming courses
around the world, and one of the most obscure topic for the developers, often
also very senior ones.
We'll explore the topic together by walking through cases in the Java world. We'll
also delve into novel approaches that can simplify it, such as Actors and
Software Transactional Memory.
DISCLAIMER: this presentation was made for a speech at CodeCamp. It was a very interactive presentation, so most of the explanations / teaching
were given by my voice, and are not present in text in the presentation, because I wanted to force the people to think, talk, interact.
I hope you can understand anyways the topic and what I wanted to give as an overall message.
2 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
3. Agenda
1. Concurrent and Parallel Computing
2. Why parallel computing matters?
3. Threading in Java
4. Common Pitfalls
3
5. Solutions
6. Novel Approaches
Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
4. Concurrent and Parallel Computing
What’s the difference?
Concurrent computing
Computing in which computations are executing during overlapping time
periods – concurrently – instead of sequentially (one completing before
the next starts)
Parallel computing
Computing in which computations are carried out simultaneously, in
parallel
They have the same hardware/software requirements?
What’s the relationship between them?
One is a super-set of the other? They are mutually exclusive?
They share the same risks, the same dangers?
4 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
5. Why parallel computing matters?
From Moore to Amdahl
Moore’s Law
over the history of
computing hardware, the
number of transistors in a
dense integrated circuit
doubles approximately
every two years
Amdahl’s Law
Maximum speedup of parallel
computing is limited by the
fraction of the problem that
must be performed
sequentially
What does it mean for performance?
What does it mean for the programmer?
What does it mean for the user?
5 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
6. Threading in Java
So easy, yet so complex
EASY
DANGEROUS
COMPLEX
NOT KNOWN
NOT TAUGHT
NOT DOCUMENTED
BITES YOU IN THE (_!_)
… really?
6 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
7. Threading in Java
Quotes on parallel computing
“The way the processor industry is going, is to add more and more cores, but nobody knows
how to program those things. I mean, two, yeah; four, not really; eight, forget it.”
Steve Jobs, Apple
“Everybody who learns concurrency thinks they understand it, ends up finding mysterious
races they thought weren’t possible, and discovers that they didn’t actually understand it yet
after all.”
Herb Sutter, chair of the ISO C++ standards committee, Microsoft.
“I decided long ago to stick to what I know best. Other people understand parallel machines
much better than I do; programmers should listen to them, not me, for guidance on how to
deal with simultaneity.”
Donald Knuth, Professor Emeritus at Stanford University
“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the
code as cleverly as possible, you are, by definition, not smart enough to debug it.”
Brian Kernighan, professor at Princeton University
7 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
8. Threading in Java
So easy, yet so complex
EASY
Can it get easier than this?
Can you do without threads?
Where are threads?
8 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
9. Threading in Java
So easy, yet so complex
DANGEROUS
What is Thread Safety?
A class is thread-safe if it behaves correctly when accessed from multiple threads,
regardless of the scheduling or interleaving of the execution of those threads by the runtime
environment, and with no additional synchronization or other coordination on the part of the
calling code.
How it becomes dangerous?
Without proper synchronization the JVM is designed to exploit any possible optimization,
relaxing the guarantees and semantics of the java code in multi-threading environments, in
order to ensure maximum performance for the code when single-threaded.
How can I fix it?
Basically the assumption is that you know when your classes will be accessed by multiple
threads, you know what the dangers are, and you will take proper actions to notify the
JVM of this, and ensure proper behavior using the tools java offers (synchronized, volatile,
etc…)
And of course you know that perfectly right?
9 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
10. Threading in Java
So easy, yet so complex
COMPLEX
Understanding concurrent/parallel programming and threading in Java, means
understanding in details the Java Language Specification, and how Java Memory
Model works (JSR 133), and the partial-ordering rules (“happens-before”) that are
defined there
“The Java Memory Model describes what behaviors are legal in multithreaded code, and
how threads may interact through memory. It describes the relationship between variables
in a program and the low-level details of storing and retrieving them to and from memory or
registers in a real computer system. It does this in a way that can be implemented correctly
using a wide variety of hardware and a wide variety of compiler optimizations.”
Brian Goetz
10 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
11. Threading in Java
So easy, yet so complex
COMPLEX
What you need to know
Safely share mutable state across threads
Ensure proper visibility and avoid reading stale/partial values
Manage correctly JVM low-level optimization to not affect the software semantics
Avoid deadlocks and livelocks situations
Know what is thread-safe and what not and use them accordingly
Properly use the tools java offers (immutable objects, volatile keyword, implicit/explicit locking, atomic variables,
synchronized/concurrent collections, blocking queues and deques, latches, semaphores, barriers, phasers, executors,
FutureTask, fork-join framework, parallel bulk operations, non-blocking synchronization, thread and stack confinement,
client-side locking, safe publication, fail-fast iterators, lock striping, piggybacking, copy-on-write)
Minimize critical sections, avoid unneeded bottlenecks and maximize code performance in multi-core scenarios
You tick all the checkboxes right?
11 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
12. Threading in Java
So easy, yet so complex
NOT KNOWN
The seniors and gurus who know it, they THINK they know it, but actually, they don’t
The ones who do know it for real, are the ones that will tell you that it’s a very
complex topic, and that they really don’t know it all
Where do you think you stand here?
Most junior programmers don’t know it
Most senior programmers don’t know it
Most “guru“ programmers don’t know it
12 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
13. Threading in Java
So easy, yet so complex
NOT TAUGHT
In Education: while threading is so ubiquitous, it’s considered an ‘advanced topic’ and it’s
mostly not taught at all in schools and universities. Not to mention the fact that most
teachers do not actually know anything about it (there are exceptions of course! )
In Books: most people who write java books, do not really understand the topic, and
therefore do not really teach it (example: most sold and known Java book by Bruce Eckel
took 10+ years and 4 editions to include a proper and correct discussion of the topic)
In Online Articles: … they are too busy speaking about “The Cloud” (whatever that means)
or showing you how to build in 5 minutes and 10 easy steps a “HelloWorld” web application
in the last fancy, trendy framework
In Companies: you have to deliver for yesterday, something based on the requirements
that will come in tomorrow…. you think you have time to think about thread safety??
Did someone or something teach you about this topic?
13 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
14. Threading in Java
So easy, yet so complex
NOT DOCUMENTED
Documentation is one of the most powerful tools for managing thread safety. Users look to the
documentation to find out if a class is thread-safe, and maintainers look to the documentation to
understand the implementation strategy so they can maintain it without inadvertently compromising
safety
but….
Most of Java frameworks, API, libraries, technologies very poorly document their thread-safety and
threading behaviors, if they do at all.
Even official java libraries are no exception: more often than not, you have to make assumptions
based on common sense, because java technologies specification are silent, or at least
unforthcoming, about thread safety guarantees and requirements for interfaces to implement
Try to look for words “thread” or “concurrent” in JDBC specifications
Is a ServletContext thread-safe? A HttpSession? A DataSource?
14 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
15. Threading in Java
So easy, yet so complex
BITES YOU IN THE ***
Multi-threading bugs are the kind of bug that:
Can wreck havoc: visibility/reordering issues can make your application read old or even completely wrong values in a
variable, dead and live locks situation can make your application hang totally or run and use 100% of the hardware
resources without doing any progress. Think about what this can do to the real-world application you manage.
You will be fired faster than you can read the Exception message.
Are impossible to replicate: for 1.000.000.000 times it works correctly, then it doesn’t work correctly for one time, then it
works correctly again for another 1.000.000.000 times. Good luck debugging that.
Choose their target well: they work correctly on your development machine (one processor, less cores, client JVM), they
fail on the production machine (multi-processors, more cores, server JVM). That’s unfair I know.
You are naked against them: you have almost no tools to defend yourself. How can you detect or debug something that
happens once every 3 months and manifest in completely unknown behavior? The only way is pain-stakingly going through
*ALL* your code to find where the threading issue is. Good luck with that too.
Do you still want to write multi-threaded software?
15 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
16. Threading in Java
So easy, yet so complex
… really? Yes. Really.
Seems simple enough, isn’t it?
16 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
17. Threading in Java
So easy, yet so complex
Challenge
You think you know the answer?
#ReplyIfYouCan
Post on twitter using hashtag #ReplyIfYouCan the solution to this challenge
Anyone can participate, you have time until Sunday 26th October 2014, 23.59 to
submit your answer. At that time, I will post the ‘solution’ to the challenge.
The best answer will be selected for a special prize offered by UniCredit Business
Integrated Solutions, and will be given a job opportunity for an IT career in Iasi
Anyone up to the challenge?
17 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
18. Threading in Java
So easy, yet so complex
So, where are the problems?
ATOMICITY
Whenever a program has instructions that should be logically connected one to the other (i.e. “Check Then Act” or “If Then
Else” logic), I have to ensure that the instructions are executed in an atomic way (all, or none) in a multi-threading
environment, otherwise race conditions could arise that violate the program intended behavior
VISIBILITY
In a multi-threading environment, due to optimizations techniques used by the VM and JIT Compiler, there is no guarantee of
visibility of mutable state across threads. Whenever I share state across threads, I have to make sure to take the proper
steps to notify this to the VM, so to enforce necessary actions to achieve visibility
ORDERING
The JVM specifications allows the JVM to freely re-order instructions in any program, and not execute them strictly in
order, but instead re-ordering them in a more efficient way for performance purpose, as long as this re-ordering do not
affect the intended behavior in single-thread environment. This effectively means that in multi-threading environment I
have to understand what the re-ordering could mean, and take proper action to tell the JVM not to do it, in case it would
break the correct program execution
Scary stuff isn’t it?
18 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
19. Common Pitfalls
If you have done this, don’t worry, you are not alone
How would you fix this?
ATOMICITY
19 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
20. Common Pitfalls
If you have done this, don’t worry, you are not alone
How would you fix this?
ATOMICITY
20 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
21. Common Pitfalls
If you have done this, don’t worry, you are not alone
How would you fix this?
VISIBILITY
21 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
22. Common Pitfalls
If you have done this, don’t worry, you are not alone
How would you fix this?
VISIBILITY
22 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
23. Common Pitfalls
If you have done this, don’t worry, you are not alone
How would you fix this?
ORDERING
23 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
24. Solutions
…. Ahhh finally!
Now I KNOW how to fix this!
STATELESS
CONFINEMENT
VOLATILE
LOCKING
IMMUTABLE
THREAD-SAFE CLASSES
24 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
25. Solutions
…. Ahhh finally!
Now I KNOW how to fix this!
STATELESS
if you have no state, you have no risk
25 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
26. Solutions
…. Ahhh finally!
if your state can only be accessed by one thread, you’re safe
Now I KNOW how to fix this!
CONFINEMENT
26 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
27. Solutions
…. Ahhh finally!
when you have shared state, and you need to enforce visibility ONLY, use volatile
Now I KNOW how to fix this!
VOLATILE
27 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
28. Solutions
…. Ahhh finally!
when you have shared state, and you need to enforce visibility AND atomicity, synchronize
Now I KNOW how to fix this!
LOCKING
28 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
29. Solutions
…. Ahhh finally!
Now I KNOW how to fix this!
IMMUTABLE
Immutable objects are always thread-safe
29 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
30. Solutions
…. Ahhh finally!
Now I KNOW how to fix this!
IMMUTABLE
Immutable objects are always thread-safe
30 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
31. Solutions
…. Ahhh finally!
when you can’t do something, ask someone else to do it
Now I KNOW how to fix this!
THREAD-SAFE CLASSES
31 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
32. Solutions
Let’s see what Java offers us…
Fail-fast and fail-safe iterators: almost all non-thread safe java collections offers fail-fast iterators, that
in most cases gives ConcurrentModificationException when used incorrectly, to help detecting threading
issues, and most concurrent collections offers fail-safe iterators, which are thread-safe by default
Easy ways to ensure immutability and to force confinement: final keyword, ThreadLocal* classes
Direct un-optimized memory access: with keyword “volatile” you can force the read and write directly
to central memory and ensure no caching/optimization interfere (and no instruction re-ordering since
Java5, when it became also a full memory barrier), giving you a fast and easy solution to simple visibility
issues
Implicit and Explicit Locking: you have at your disposal exclusive implicit locking through the
“synchronized” keyword, but you can also explicit lock classes such as ReentrantLock,
ReentrantReadWriteLock, that gives more flexibility over dealing with lock unavailability and greater control
over queueing behavior (fair vs unfair lock, read-write, etc…)
Atomic classes: many atomic classes that are thread-safe, are very fast (due to native support for
Compare-and-Swap CAS hardware CPU instructions) and also allows thread-safe compound operations
like addAndGet, compareAndSet, etc.. (AtomicInteger, AtomicLongArray, AtomicReference, etc…)
Learn these tools and use them!
32 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
33. Solutions
Let’s see what Java offers us…
Thread-safe classes and wrappers: many thread-safe classes for a lot of different operations
(StringBuffer, etc…), thread-safe collections (CopyOnWriteArrayList, etc…), and library wrappers to make
collections thread-safe through exclusive locking (Collections.synchronizedList/Map/Set, etc…)
Concurrent collections: concurrent collections that are thread-safe, very fast, and with support for
compound operations, through implementation approaches like copy-on-write, lock-striping, piggybacking
and other non-blocking lock-free advanced synchronization techniques (CopyOnWriteArrayList/Set,
ConcurrentHashMap, ConcurrentSkipListSet/Map, ConcurrentLinkedQueue/Deque,
PriorityBlockingQueue, LinkedTransferQueue, SynchronousQueue, etc…)
Synchronizers: when you need to coordinate the work and lifecycle of multiple threads, you have a lot
of different classes to help you do so (CountDownLatch, CyclicBarrier, Semaphore, Phaser, Exchanger,
etc…)
Threading Tools: when you need to manage multiple threads for tasks and pool/re-use them, you have
a lot of threading pool possibilities, executor services and tools to facilitate the job (FutureTask, Executor,
ExecutorService, ThreadFactory, ScheduledExecutorService, CompletionService, Fork-join framework,
Thread.isInterrupted()/interrupted(), daemon threads, etc..)
Learn these tools and use them!
33 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
34. Novel Approaches
Going forward
34 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
35. Novel Approaches
Going forward
LOCKING
35 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
36. Novel Approaches
Going forward
LOCKS
PRO
Available: synchronization primitives are
available by default in any modern
programming language, Java included
Flexible: by mixing all the tools that you
have at your disposal, you can achieve and
implement exactly the concurrency model and
architecture you need for your purpose
Fast: nothing beats being able to write your
very own thread-synchronization code at the
lowest level possible, using volatile, atomics,
locks, synchronizers
CONS
Knowledge: require a very deep knowledge
of the Java Language Specification and Java
Memory Model to fully grasp the concepts
behind and master them (“happens-before”)
Complicated: managing threading
primitives at the lowest level possible is often a
big task, and cumbersome, it’s a big effort on
its own
Error-prone: it’s very easy to forget to
properly handle one corner case, and suddenly
turn one perfectly thread-safe class into a
broken one
36 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
37. Novel Approaches
Going forward
ACTORS
37 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
38. Novel Approaches
Going forward
ACTORS
Actors are very lightweight concurrent entities. They hold the state, and encapsulate the programming
logic, and interact with each other through asynchronous messages and message queues. They raise the
abstraction level and make it much easier to write, test, understand and maintain concurrent and/or
distributed systems. You focus on workflow—how the messages flow in the system—instead of low level
primitives like threads, locks and socket IO
PRO
Safe: no shared state, and no blocking, so
your software is safe “by default”
High Level: you don’t have to deal with
threading primitives, and you can focus on the
real task at hand
CONS
Restructuring & Rethinking: if you want to
use actors, ALL your code will need to use
actors, and all your code will need to be
written, designed and thought using actors and
message handling
Are you ready to *THINK* in actors?
38 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
39. Novel Approaches
Going forward
SOFTWARE TRANSACTIONAL MEMORY
How would you fix this?
39 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
40. Novel Approaches
Going forward
SOFTWARE TRANSACTIONAL MEMORY
Software transactional memory (STM) is a concurrency control mechanism analogous to database
transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock-based
synchronization. A transaction in this context occurs when a piece of code executes a series of
reads and writes to shared memory. These reads and writes logically occur at a single instant in time;
intermediate states are not visible to other (successful) transactions.
PRO
Increased concurrency: thanks to
optimistic approach no thread needs to wait for
a resource, and different threads can safely
access same resource
Straightforward: you just need to mark the
transaction sections that you need to be
atomic, but you don’t have to reason about the
state, variables, conditions
CONS
Repeatable operations: every critical
sections needs to be re-executed if it fails to
‘commit’, so it means that side-effects could
trigger twice, and that do-once operations,
such as I/O, cannot be handled this way
Overhead: maintaining the log, and doing
transactions verification and commits cost time
and performance, and so does repeating
operations again and again potentially
40 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions
41. Thread with care: concurrency pitfalls in Java
Luigi Lauro - Luigi.Lauro@unicredit.eu
Online Articles:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
http://www.vogella.com/tutorials/JavaConcurrency/article.html
http://baptiste-wicht.com/posts/2010/05/java-concurrency-part-1-threads.html
http://www.javaworld.com/article/2078809/java-concurrency/
http://adit.io/posts/2013-05-15-Locks,-Actors,-And-STM-In-Pictures.html
Get in touch with me at Luigi.Lauro@unicredit.eu for asking to have this presentation, for
questions, doubts, solutions, discussions, insults, suggestions, and pretty much everything!
That’s all folks!
Books:
Java Concurrency in Practice - Brian Goetz
Concurrent Programming in Java - Doug Lea
The Art of Multiprocessor Programming - Maurice Herlihy
Programming Concurrency on the JVM - Venkat Subramaniam
Seven Concurrency Models in Seven Weeks - Paul Butcher
41 Iași, 25 October 2014 Luigi Lauro - UniCredit Business Integrated Solutions