This document discusses common concurrency problems in Java and how to address them. It covers issues that can arise from shared mutable data being accessed without proper synchronization between threads, as well as problems related to visibility and atomicity of operations. Specific problems covered include mutable statics, double-checked locking, volatile arrays, and non-atomic operations like incrementing a long. The document provides best practices for locking, wait/notify, thread coordination, and avoiding deadlocks, spin locks, and lock contention.
After an overview of Qt and its tools, a Hello World application quickly demonstrates the basic principles.
Qt is mainly famous for its intelligent concepts of signals and slots, which is explained together with examples for how to use widgets (UI controls).
At the end, the foundations of the meta-object system and its implications on memory management are explained.
This module follows up the introduction in the "Software Development with Qt" module, plus the Quickstart slides.
Grand Central Dispatch (GCD) dispatch queues are a powerful tool for performing tasks. Dispatch queues let you execute arbitrary blocks of code either asynchronously or synchronously with respect to the caller.
After an overview of Qt and its tools, a Hello World application quickly demonstrates the basic principles.
Qt is mainly famous for its intelligent concepts of signals and slots, which is explained together with examples for how to use widgets (UI controls).
At the end, the foundations of the meta-object system and its implications on memory management are explained.
This module follows up the introduction in the "Software Development with Qt" module, plus the Quickstart slides.
Grand Central Dispatch (GCD) dispatch queues are a powerful tool for performing tasks. Dispatch queues let you execute arbitrary blocks of code either asynchronously or synchronously with respect to the caller.
Multithreading with modern C++ is hard. Undefined variables, Deadlocks, Livelocks, Race Conditions, Spurious Wakeups, the Double Checked Locking Pattern, etc. And at the base is the new Memory-Modell which make the life not easier. The story of things which can go wrong is very long. In this talk I give you a tour through the things which can go wrong and show how you can avoid them.
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
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
Kotlin is a language that is rapidly gaining popularity, among others thanks to cooperation with Java. On the other hand, RxJava has brought us many solutions to problems related to asynchronous code. If everything is so cool, do we need anything else in the Kotlin world? Is Kotlin Coroutine a competition for RxJava?
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Kyung Koo Yoon
Lecture on Java Concurrency Day 4 on Feb 18, 2009. (in Korean)
Lectures are 4 days in all.
See http://javadom.blogspot.com/2011/06/lecture-on-java-concurrency-day-4.html
GPars is a concurrency and parallelism toolkit for the JVM. Founded on java.util.concurrent, it extends it with additional models of concurrency and parallelism, e.g. dataflow, CSP, actors, agents. Although GPars requires Groovy to run it is a toolkit usable from Java as well as Groovy codes.
This was presented at DevoxxUK 2013 2013-03-27T15:50
Multithreading with modern C++ is hard. Undefined variables, Deadlocks, Livelocks, Race Conditions, Spurious Wakeups, the Double Checked Locking Pattern, etc. And at the base is the new Memory-Modell which make the life not easier. The story of things which can go wrong is very long. In this talk I give you a tour through the things which can go wrong and show how you can avoid them.
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
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
Kotlin is a language that is rapidly gaining popularity, among others thanks to cooperation with Java. On the other hand, RxJava has brought us many solutions to problems related to asynchronous code. If everything is so cool, do we need anything else in the Kotlin world? Is Kotlin Coroutine a competition for RxJava?
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Kyung Koo Yoon
Lecture on Java Concurrency Day 4 on Feb 18, 2009. (in Korean)
Lectures are 4 days in all.
See http://javadom.blogspot.com/2011/06/lecture-on-java-concurrency-day-4.html
GPars is a concurrency and parallelism toolkit for the JVM. Founded on java.util.concurrent, it extends it with additional models of concurrency and parallelism, e.g. dataflow, CSP, actors, agents. Although GPars requires Groovy to run it is a toolkit usable from Java as well as Groovy codes.
This was presented at DevoxxUK 2013 2013-03-27T15:50
Using Groovy? Got lots of stuff to do at the same time? Then you need to take a look at GPars (“Jeepers!”), a library providing support for concurrency and parallelism in Groovy. GPars brings powerful concurrency models from other languages to Groovy and makes them easy to use with custom DSLs:
- Actors (Erlang and Scala)
- Dataflow (Io)
- Fork/join (Java)
- Agent (Clojure agents)
In addition to this support, GPars integrates with standard Groovy frameworks like Grails and Griffon.
Background, comparisons to other languages, and motivating examples will be given for the major GPars features.
Lecture 10 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
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.
While Google is adding Kotlin as an official Android language, we're also expanding our research on this language. It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise and makes coding a satisfying and efficient experience.
Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
Please see my presentation to learn more!
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
One of the greatest benefits of Clojure is its ability to create simple, powerful abstractions that operate at the level of the problem while also operating at the level of the language.
This talk discusses a query processing engine built in Clojure that leverages this abstraction power to combine streams of data for efficient concurrent execution.
* Representing processing trees as s-expressions
* Streams as sequences of data
* Optimizing processing trees by manipulating s-expressions
* Direct execution of s-expression trees
* Compilation of s-expressions into nodes and pipes
* Concurrent processing nodes and pipes using a fork/join pool
Stream Execution with Clojure and Fork/joinAlex Miller
One of the greatest benefits of Clojure is its ability to create simple, powerful abstractions that operate at the level of the problem while also operating at the level of the language.
This talk discusses a query processing engine built in Clojure that leverages this abstraction power to combine streams of data for efficient concurrent execution.
* Representing processing trees as s-expressions
* Streams as sequences of data
* Optimizing processing trees by manipulating s-expressions
* Direct execution of s-expression trees
* Compilation of s-expressions into nodes and pipes
* Concurrent processing nodes and pipes using a fork/join pool
Maybe you've heard of Clojure, one of those new-fangled JVM languages. How does anybody get any work done in a language like that? What's up with all those parentheses?
If you're coming from Java and OOP, Clojure can indeed feel disorienting. In this talk we'll demystify the basics of Clojure and dissect the source of its power. Functional programming is on the rise and Clojure is indeed a functional language, but we'll learn the real secret sauce that makes cooking with Clojure fun.
We'll look at how to translate concepts you know in Java (like domain objects, interfaces, collections, and concurrency) into their natural Clojure equivalents. And more importantly, we'll learn how these components interact to make Clojure a beautiful language for building abstractions.
No prior knowledge of Clojure or functional programming is assumed... Clojure novices welcome!
Releasing Relational Data to the Semantic WebAlex Miller
Enterprises are drowning in data that they can't find, access, or use.
For many years, enterprises have wrestled with the best way to combine all that data into actionable information without building systems that break as schemas evolve. Approaches like warehousing and ETL can be brittle in the face of changing data sources or expensive to create. Data integration at the application level is common but this results in significant complexity in the code. Data-oriented web services attempt to provide reusable sources of integrated data, however these have just added another layer of data access that constrain query and access patterns.
This talk will look at how semantic web technologies can be used to make existing data visible and actionable using standards like RDF (data), R2RML (data translation), OWL (schema definition and integration), SPARQL (federated query), and RIF (rules). The semantic web approach takes the data you already have and makes that data available for query and use across your existing data sources. This base capability is an excellent platform for building federated analytics.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
A talk about doing innovative software development including embracing constraints, iterating towards product/market fit, and the qualities of a great innovative team. This presentation was given at the St. Louis Innovation Camp in Feb, 2010.
Caching has been an essential strategy for greater performance in computing since the beginning of the field. Nearly all applications have data access patterns that make caching an attractive technique, but caching also has hidden trade-offs related to concurrency, memory usage, and latency.
As we build larger distributed systems, caching continues to be a critical technique for building scalable, high-throughput, low-latency applications. Large systems tend to magnify the caching trade-offs and have created new approaches to distributed caching. There are unique challenges in testing systems like these as well.
Ehcache and Terracotta provide a unique way to start with simple caching for a small system and grow that system over time with a consistent API while maintaining low-latency, high-throughput caching.
Scaling Your Cache And Caching At ScaleAlex Miller
Caching has been an essential strategy for greater performance in computing since the beginning of the field. Nearly all applications have data access patterns that make caching an attractive technique, but caching also has hidden trade-offs related to concurrency, memory usage, and latency.
As we build larger distributed systems, caching continues to be a critical technique for building scalable, high-throughput, low-latency applications. Large systems tend to magnify the caching trade-offs and have created new approaches to distributed caching. There are unique challenges in testing systems like these as well.
Ehcache and Terracotta provide a unique way to start with simple caching for a small system and grow that system over time with a consistent API while maintaining low-latency, high-throughput caching.
Terracotta (an open source technology) provides a clustered, durable virtual heap. Terracotta's goal is to make Java apps scale with as little effort as possible. If you are using Hibernate, there are several patterns that can be used to leverage Terracotta and reduce the load on your database so your app can scale.
First, you can use the Terracotta clustered Hibernate cache. This is a high-performance clustered cache and allows you to avoid hitting the database on all nodes in your cluster. It's suitable, not just for read-only, but also for read-mostly and read-write use cases, which traditionally have not been viewed as good use cases for Hibernate second level cache.
Another high performance option is to disconnect your POJOs from their Hibernate session and manage them entirely in Terracotta shared heap instead. This is a great option for conversational data where the conversational data is not of long-term interest but must be persistent and highly-available. This pattern can significantly reduce your database load but does require more changes to your application than using second-level cache.
This talk will examine the basics of what Terracotta provides and examples of how you can scale your Hibernate application with both clustered second level cache and detached clustered state. Also, we'll take a look at Terracotta's Hibernate-specific monitoring tools.
A preview of likely features that will be included in Java 7 / JDK 7. Note that this presentation is from February 2009 and things are changing quickly.
How Terracotta enables scaled Spring/Hibernate applications. Presented at Chicago JUG in March 2009 by Alex Miller (http://tech.puredanger.com / @puredanger)
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!
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
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/
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.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
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.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
2. Questions to answer
> What are common concurrency problems?
> Why are they problems?
> How do I detect these problems?
> How do I correct these problems?
2
8. Mutable Statics
public class MutableStatics {
FORMAT is mutable
private static final DateFormat FORMAT =
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static Date parse(String str)
throws ParseException {
...and this mutates it
return FORMAT.parse(str);
outside synchronization
}
public static void main(String arg[]) {
MutableStatics.parse(“Jan 1, 2000”);
}
}
7
9. Mutable Statics - instance per call
public class MutableStatics {
public static Date parse(String str)
throws ParseException {
DateFormat format =
DateFormat.getDateInstance(DateFormat.MEDIUM);
return format.parse(str);
}
public static void main(String arg[]) {
MutableStatics.parse(“Jan 1, 2000”);
}
}
8
14. DO NOT synchronize on string literals
private static final String LOCK = “LOCK”;
synchronized( LOCK ) {
What is the scope
// work of LOCK?
}
13
15. DO NOT synchronize on autoboxed instances
private static final Integer LOCK = 0;
synchronized( LOCK ) {
What is the scope
// work of LOCK?
}
14
16. DO NOT synchronize on ReentrantLock
final Lock lock = new ReentrantLock();
synchronized( lock ) { Probably not what
// work you meant here
}
final Lock lock = new ReentrantLock();
lock.lock();
Probably should
try { be this instead
// ...
} finally {
lock.unlock();
}
15
17. What should I lock on?
// The field you are protecting
private final Map map = ...
synchronized(map) {
// ...access map
}
// Or an explicit lock object
private final Object lock = new Object();
synchronized(lock) {
// ... modify state
}
16
19. Inconsistent Synchronization
public class SomeData {
private final Map data = new HashMap();
public void put(String key, String value) {
synchronized(data) {
data.put(key, value); Modified under synchronization
}
}
public String get(String key) {
return data.get(key); Read without synchronization
}
}
18
20. Double-checked locking
public final class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if(instance == null) { Attempt to avoid synchronization
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
19
21. Double-checked locking
public final class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if(instance == null) { READ
synchronized(Singleton.class) {
if(instance == null) { READ
instance = new Singleton(); WRITE
}
}
}
return instance;
}
}
19
22. Double-checked locking - volatile
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return INSTANCE;
}
20
23. Double-checked locking - initialize on demand
public class Singleton {
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
21
24. Racy single-check
public final class String {
private int hash; // default to 0
private final char[] value; // immutable
public int hashCode() {
int h = hash;
if(h == 0) {
// ... compute value for h from data
hash = h;
}
return h;
}
}
22
25. volatile arrays
public final class VolatileArray {
private volatile boolean[] vals;
public void flip(int i) {
vals[i] = true; Is the value of vals[i]
} visible to other threads?
public boolean flipped(int i) {
return vals[i];
}
}
23
27. Volatile counter
public class Counter {
private volatile int count;
public int next() {
return count++; Looks atomic to me!
}
}
25
28. AtomicInteger counter
public class Counter {
private final AtomicInteger count = new AtomicInteger();
public int next() {
Really atomic by
return count.getAndIncrement(); encapsulating
} multiple actions
}
26
29. Composing atomic actions
public Object putIfAbsent(
Hashtable table, Object key, Object value) {
Hashtable is thread-safe
if(table.containsKey(key)) { READ
// already present, return existing value
return table.get(key); READ
} else {
// doesn’t exist, create and return new value
table.put(key, value); WRITE
return value;
}
}
27
30. Composing atomic actions
public Object putIfAbsent(
Hashtable table, Object key, Object value) {
Hashtable is thread-safe
if(table.containsKey(key)) { READ
// already present, return existing value
return table.get(key); READ
} else {
// doesn’t exist, create and return new value
table.put(key, value); WRITE
return value;
}
}
27
33. Assignment of 64 bit values
public class LongAssignment {
private long x;
public void setLong(long val) {
x = val; Looks atomic to me -
} but is it?
}
30
34. Assignment of 64 bit values - volatile
public class LongAssignment {
private volatile long x;
public void setLong(long val) {
x = val;
}
}
31
36. Listener in constructor
public interface DispatchListener {
void newFare(Customer customer);
}
public class Taxi implements DispatchListener {
public Taxi(Dispatcher dispatcher) {
dispatcher.registerListener(this);
We just published a
// other initialization reference to this - oops!
}
public void newFare(Customer customer) {
// go to new customer's location
}
}
33
37. Starting thread in constructor
public class Cache {
private final Thread cleanerThread;
public Cache() { this escapes again!
cleanerThread = new Thread(new Cleaner(this));
cleanerThread.start();
}
// Cleaner calls back to this method
public void cleanup() {
// clean up Cache
}
}
34
38. Static factory method
public class Cache {
// ...
public static Cache newCache() {
Cache cache = new Cache();
cache.startCleanerThread();
return cache;
}
}
35
45. Spin wait
// Not efficient
private volatile boolean flag = false;
public void waitTillChange() {
while(! flag) {
Spin on flag,
Thread.sleep(100); waiting for change
}
}
public void change() {
flag = true;
}
42
46. Replace with wait/notify
private final Object lock = new Object();
private boolean flag = false;
public void waitTillChange() {
synchronized(lock) {
while(! flag) Wait/notify is far more
lock.wait(); efficient than spin wait.
}
}
public void change() {
synchronized(lock) {
flag = true;
lock.notifyAll();
}
}
43
49. Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
private long queryExecutionCount;
public synchronized void queryExecuted(String hql, int rows, long
time) {
queryExecutionCount++;
// ... other stat collection
}
public long getQueryExecutionCount() {
return queryExecutionCount;
}
public synchronized void clear() {
queryExecutionCount = 0;
// ... clear all other stats
}
}
46
50. Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
private long queryExecutionCount;
public synchronized void queryExecuted(String hql, int rows, long
time) {
queryExecutionCount++;
// ... other stat collection
}
public long getQueryExecutionCount() {
return queryExecutionCount;
Read of shared value
}
without synchronization
public synchronized void clear() {
queryExecutionCount = 0;
// ... clear all other stats
}
}
46
51. Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
private long queryExecutionCount;
public synchronized void queryExecuted(String hql, int rows, long
time) {
queryExecutionCount++;
// ... other stat collection
}
public long getQueryExecutionCount() {
return queryExecutionCount;
Read of shared value Non-atomic read
}
without synchronization of long value
public synchronized void clear() {
queryExecutionCount = 0;
// ... clear all other stats
}
}
46
52. Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
private long queryExecutionCount;
public synchronized void queryExecuted(String hql, int rows, long
time) {
queryExecutionCount++;
// ... other stat collection
}
public long getQueryExecutionCount() {
return queryExecutionCount;
Read of shared value Non-atomic read
}
without synchronization of long value
public synchronized void clear() {
queryExecutionCount = 0;
Race condition if reading stat and
// ... clear all other stats clearing - could be compound action
}
}
46
53. Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
private long queryExecutionCount;
public synchronized void queryExecuted(String hql, int rows, long
time) {
Single shared lock for ALL stat values
queryExecutionCount++;
// ... other stat collection
}
public long getQueryExecutionCount() {
return queryExecutionCount;
Read of shared value Non-atomic read
}
without synchronization of long value
public synchronized void clear() {
queryExecutionCount = 0;
Race condition if reading stat and
// ... clear all other stats clearing - could be compound action
}
}
46