Java Platform Concurrency Gotchas

Size: px
Start display at page:

Download "Java Platform Concurrency Gotchas"

Transcription

1 Java Platform Concurrency Gotchas Alex Miller Terracotta

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

3 Taxonomy of Concurrency Gotchas > Shared Data > Coordination > Performance 3

4 Shared Data > Locking > Visibility > Atomicity > Safe Publication 4

5 What happens if we modify data without locking? 5

6 What happens if we modify data without locking? Hint: itʼs not good. 5

7 6

8 Mutable Statics public class MutableStatics { private static final DateFormat FORMAT = DateFormat.getDateInstance(DateFormat.MEDIUM); public static Date parse(string str) throws ParseException { return FORMAT.parse(str); FORMAT is mutable...and this mutates it 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

10 Synchronization private int myfield; synchronized( What goes here? ) { myfield = 0; 9

11 DO NOT synchronize on null MyObject obj = null; synchronized( obj ) { // stuff NullPointerException! 10

12 DO NOT change instance MyObject obj = new MyObject(); synchronized( obj ) { obj = new MyObject(); No longer synchronizing on the same object! 11

13 12

14 DO NOT synchronize on string literals private static final String LOCK = LOCK ; synchronized( LOCK ) { // work What is the scope of LOCK? 13

15 DO NOT synchronize on autoboxed instances private static final Integer LOCK = 0; synchronized( LOCK ) { // work What is the scope of LOCK? 14

16 DO NOT synchronize on ReentrantLock final Lock lock = new ReentrantLock(); synchronized( lock ) { // work Probably not what you meant here final Lock lock = new ReentrantLock(); lock.lock(); try { //... finally { lock.unlock(); Probably should be this instead 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

18 Visibility 17

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) { synchronized(singleton.class) { if(instance == null) { instance = new Singleton(); return instance; Attempt to avoid synchronization 19

21 Double-checked locking public final class Singleton { private static Singleton instance; public static Singleton getinstance() { if(instance == null) { synchronized(singleton.class) { if(instance == null) { instance = new Singleton(); return instance; READ READ WRITE 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

26 Atomicity 24

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() { return count.getandincrement(); Really atomic by encapsulating multiple actions 26

29 Composing atomic actions public Object putifabsent( Hashtable table, Object key, Object value) { if(table.containskey(key)) { // already present, return existing value return table.get(key); else { // doesn t exist, create and return new value Hashtable is thread-safe table.put(key, value); return value; READ READ WRITE 27

30 Composing atomic actions public Object putifabsent( Hashtable table, Object key, Object value) { if(table.containskey(key)) { // already present, return existing value return table.get(key); else { // doesn t exist, create and return new value Hashtable is thread-safe table.put(key, value); return value; READ READ WRITE 27

31 Participate in lock public Object putifabsent( Hashtable table, Object key, Object value) { synchronized(table) { if(table.containskey(key)) { return table.get(key); else { table.put(key, value); return value; Protect with synchronization 28

32 Encapsulated compound actions public Object putifabsent( ConcurrentHashMap table, Object key, Object value) { table.putifabsent(key, value); 29

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

35 Safe publication Intentionally left blank. 32

36 Listener in constructor public interface DispatchListener { void newfare(customer customer); public class Taxi implements DispatchListener { public Taxi(Dispatcher dispatcher) { dispatcher.registerlistener(this); // other initialization We just published a 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; this escapes again! public Cache() { 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

39 Coordination > Threads > wait/notify 36

40 Threads > DO NOT: Call Thread.stop() Call Thread.suspend() or Thread.resume() Call Thread.destroy() Call Thread.run() Use ThreadGroups 37

41 wait/notify // Thread 1 synchronized(lock) { while(! somecondition()) { lock.wait(); You must synchronize. Always wait in a loop. // Thread 2 synchronized(lock) { satisfycondition(); lock.notifyall(); Synchronize here too. Update condition! 38

42 Performance > Deadlock > Spin wait > Lock contention 39

43 Deadlock // Thread 1 synchronized(lock1) { synchronized(lock2) { // stuff Classic deadlock. // Thread 2 synchronized(lock2) { synchronized(lock1) { // stuff 40

44 Deadlock avoidance > Lock splitting > Lock ordering > Lock timeout > trylock 41

45 Spin wait // Not efficient private volatile boolean flag = false; public void waittillchange() { while(! flag) { Thread.sleep(100); Spin on flag, 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) lock.wait(); public void change() { synchronized(lock) { flag = true; lock.notifyall(); Wait/notify is far more efficient than spin wait. 43

47 Lock contention x Hash f(x) Bucket 0 Bucket 1 Bucket 2 Bucket 3 44

48 Lock striping x Hash g(x) Hash f(x) Hash f(x) Bucket 0 Bucket 1 Bucket 0 Bucket 1 45

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 without synchronization Non-atomic read 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 without synchronization Non-atomic read of long value public synchronized void clear() { queryexecutioncount = 0; //... clear all other stats Race condition if reading stat and 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 without synchronization Non-atomic read of long value public synchronized void clear() { queryexecutioncount = 0; //... clear all other stats Race condition if reading stat and clearing - could be compound action 46

54 Alex Miller Terracotta Blog:

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 Common Java Concurrency pitfalls Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 About me Seasoned software engineer primarily working in the area of Identity and access management. Spent

More information

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Name: CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Directions: Test is closed book, closed notes. Answer every question; write solutions in spaces provided. Use backs of pages for scratch work. Good

More information

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

The Java Memory Model

The Java Memory Model The Java Memory Model What is it and why would I want one? Jörg Domaschka. ART Group, Institute for Distributed Systems Ulm University, Germany December 14, 2009 public class WhatDoIPrint{ static int x

More information

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 Threads and Locks, Part 2 CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 1 Goals Cover the material presented in Chapter 2 of our concurrency textbook In particular, selected material

More information

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency Java Threads Vs Processes CS6868 - Concurrent Programming Java Concurrency V. Krishna Nandivada Typically each instance of JVM creates a single process. Each process creates one or more threads. Main thread

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

Practical Concurrency. Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Practical Concurrency. Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Practical Concurrency Agenda Motivation Java Memory Model Basics Common Bug Patterns JDK Concurrency Utilities Patterns of Concurrent Processing Testing Concurrent Applications Concurrency in Java 7 2

More information

The New Java Technology Memory Model

The New Java Technology Memory Model The New Java Technology Memory Model java.sun.com/javaone/sf Jeremy Manson and William Pugh http://www.cs.umd.edu/~pugh 1 Audience Assume you are familiar with basics of Java technology-based threads (

More information

Sharing Objects Ch. 3

Sharing Objects Ch. 3 Sharing Objects Ch. 3 Visibility What is the source of the issue? Volatile Dekker s algorithm Publication and Escape Thread Confinement Immutability Techniques of safe publication Assignment 1 Visibility

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Encapsulation, Publication, Escape Data Encapsulation One of the approaches in object-oriented programming is to use data encapsulation

More information

CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects

CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects CMSC 433 Programming Language Technologies and Paradigms Sharing Objects Administrivia Are you getting your money s worth? Are you reviewing the slides? Are you experimenting with concurrency? Have you

More information

More thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction

More thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction More thread safety and Concurrent collections Nasser Giacaman CompSci 230: Software Design and Construction 1 Today's lecture More on Java's mutual exclusion tools Intrinsic locks Developing our own thread-safe

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing

More information

Buffer & File Optimization. Cloud Databases DataLab CS, NTHU

Buffer & File Optimization. Cloud Databases DataLab CS, NTHU Buffer & File Optimization Cloud Databases DataLab CS, NTHU 1 Outline Useful Java Classes for Concurrency Lock Striping Summary of File & Buffer Optimization 2 Outline Useful Java Classes for Concurrency

More information

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming. Lecture 07: Advanced Thread programming Software System Components 2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Recap How to deal with race condition in Java Using synchronised

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

CS 351 Design of Large Programs Singleton Pattern

CS 351 Design of Large Programs Singleton Pattern CS 351 Design of Large Programs Singleton Pattern Brooke Chenoweth University of New Mexico Spring 2019 The Notion of a Singleton There are many objects we only need one of: Thread pools, caches, dialog

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Java Concurrency. Towards a better life By - -

Java Concurrency. Towards a better life By - - Java Concurrency Towards a better life By - Srinivasan.raghavan@oracle.com - Vaibhav.x.choudhary@oracle.com Java Releases J2SE 6: - Collection Framework enhancement -Drag and Drop -Improve IO support J2SE

More information

Programming Paradigms for Concurrency Lecture 3 Concurrent Objects

Programming Paradigms for Concurrency Lecture 3 Concurrent Objects Programming Paradigms for Concurrency Lecture 3 Concurrent Objects Based on companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit Modified by Thomas Wies New York University

More information

Concurrency and High Performance Reloaded

Concurrency and High Performance Reloaded Concurrency and High Performance Reloaded Disclaimer Any performance tuning advice provided in this presentation... will be wrong! 2 www.kodewerk.com Me Work as independent (a.k.a. freelancer) performance

More information

CMSC 433 Spring 2013 Exam 1

CMSC 433 Spring 2013 Exam 1 CMSC 433 Spring 2013 Exam 1 Name: _ EXAMPLE SOLUTIONS Directions: Test is closed book, closed notes, closed electronics. Answer every question; write your answers in the spaces provided. If you need extra

More information

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections Dan Grossman Last Updated: May 2012 For more information, see http://www.cs.washington.edu/homes/djg/teachingmaterials/

More information

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Singleton Pattern Mar. 13, 2007 What is it? If you need to make sure that there can be one and only one instance of a class. For example,

More information

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010 CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections Tyler Robison Summer 2010 1 Concurrency: where are we Done: The semantics of locks Locks in Java Using locks for mutual

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

Northeastern University - Seattle CS5510 Professor Ian Gorton

Northeastern University - Seattle CS5510 Professor Ian Gorton Northeastern University - Seattle CS5510 Professor Ian Gorton Northeastern University 1 Week 10 CONCURRENCY II Northeastern University 2 http://jcip.net/ 3 Overview Loops/recursion and threads Readers

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 Can't live with it. Cant live without it.

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 Can't live with it. Cant live without it. Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, Part 2 Can't live with it. Cant live without it. Fall 2013 Jonathan Aldrich Charlie Garrod School

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013 Midterm #1 CMSC 433: Programming Language Technologies and Paradigms October 14, 2013 Name Instructions Do not start until told to do so! This exam has 10 double-sided pages (including this one); make

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11 Synchronisation in Java II Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Mutual exclusion in Java continued (next lecture:

More information

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 (Can't live with it, can't live without it.

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 (Can't live with it, can't live without it. Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, Part 2 (Can't live with it, can't live without it.) Spring 2013 Christian Kästner Charlie Garrod

More information

ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I

ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I ECE 587 Hardware/Software Co-Design Spring 2018 1/15 ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I Professor Jia Wang Department of Electrical and Computer Engineering

More information

Atomicity CS 2110 Fall 2017

Atomicity CS 2110 Fall 2017 Atomicity CS 2110 Fall 2017 Parallel Programming Thus Far Parallel programs can be faster and more efficient Problem: race conditions Solution: synchronization Are there more efficient ways to ensure the

More information

CS180 Review. Recitation Week 15

CS180 Review. Recitation Week 15 CS180 Review Recitation Week 15 Announcement Final exam will be held on Thursday(12/17) 8:00~10:00 AM The coverage is comprehensive Project 5 is graded. Check your score in Blackboard. Classes and Methods

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

Techniques of Java Programming: Concurrent Programming in Java

Techniques of Java Programming: Concurrent Programming in Java Techniques of Java Programming: Concurrent Programming in Java Manuel Oriol May 11, 2006 1 Introduction Threads are one of the fundamental structures in Java. They are used in a lot of applications as

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

Design of Thread-Safe Classes

Design of Thread-Safe Classes Design of Thread-Safe Classes 1 Topic Outline Thread-Safe Classes Principles Confinement Delegation Synchronization policy documentation 2 Thread-safe Class Design Process Identify the object s state (variables)

More information

F. Tip and M. Weintraub CONCURRENCY

F. Tip and M. Weintraub CONCURRENCY F. Tip and M. Weintraub CONCURRENCY SHARED-MEMORY CONCURRENCY threads execute concurrently threads communicate values via shared memory synchronization using locks 2 PITFALLS data races atomicity violations

More information

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10 Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Exercise Session 10 Today s Exercise Session Pattern of the Day Proxy Quizzes 2 Proxy Pattern Structural

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

More information

Synchronization in Java

Synchronization in Java Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Synchronization Overview Unsufficient atomicity Data races Locks Deadlock Wait /

More information

Interview Questions I received in 2017 and 2018

Interview Questions I received in 2017 and 2018 Interview Questions I received in 2017 and 2018 Table of Contents INTERVIEW QUESTIONS I RECEIVED IN 2017 AND 2018... 1 1 OOPS... 3 1. What is the difference between Abstract and Interface in Java8?...

More information

Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 2 Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5a due now Homework 5 framework goals: Functionally correct Well documented

More information

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

Lecture 17: Sharing Objects in Java

Lecture 17: Sharing Objects in Java COMP 150-CCP Concurrent Programming Lecture 17: Sharing Objects in Java Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming March 25, 2008 Reference The content of this lecture is based on

More information

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions. + Lecture 26: Concurrency Slides adapted from Dan Grossman + Today n Reading n P&C Section 7 n Objectives n Race conditions n Announcements n Quiz on Friday 1 + This week s programming assignment n Answer

More information

Persistent Data Structures and Managed References

Persistent Data Structures and Managed References Persistent Data Structures and Managed References Clojure s approach to Identity and State Rich Hickey Agenda Functions and processes Identity, State, and Values Persistent Data Structures Clojure s Managed

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

Advanced concurrent programming in Java Shared objects

Advanced concurrent programming in Java Shared objects Advanced concurrent programming in Java Shared objects Mehmet Ali Arslan 21.10.13 Visibility To see(m) or not to see(m)... 2 There is more to synchronization than just atomicity or critical sessions. Memory

More information

Races. Example. A race condi-on occurs when the computa-on result depends on scheduling (how threads are interleaved)

Races. Example. A race condi-on occurs when the computa-on result depends on scheduling (how threads are interleaved) Races A race condi-on occurs when the computa-on result depends on scheduling (how threads are interleaved) Bugs that exist only due to concurrency o No interleaved scheduling with 1 thread Typically,

More information

The Singleton Pattern. Design Patterns In Java Bob Tarr

The Singleton Pattern. Design Patterns In Java Bob Tarr The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

IntelliJ IDEA Static Code Analysis Hamlet D'Arcy

IntelliJ IDEA Static Code Analysis Hamlet D'Arcy IntelliJ IDEA Static Code Analysis Hamlet D'Arcy Canoo Engineering AG @HamletDRC http://hamletdarcy.blogspot.com Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack

More information

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Get out, you will, of this bind If, your objects, you have confined

Get out, you will, of this bind If, your objects, you have confined CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREAD SAFETY] Putting the brakes, on impending code breaks Let a reference escape, have you? Misbehave, your code will, out of the blue Get out, you will,

More information

Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection

Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection Efficient Java (with Stratosphere) Arvid Heise, Large Scale Duplicate Detection Agenda 2 Bottlenecks Mutable vs. Immutable Caching/Pooling Strings Primitives Final Classloaders Exception Handling Concurrency

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Dr.-Ing. Michael Eichberg

Dr.-Ing. Michael Eichberg Dr.-Ing. Michael Eichberg Concurrent Programming (Overview of the Java concurrency model and its relationship to other models...) (some slides are based on slides by Andy Wellings) 2 Processes vs. Threads

More information

Menu. In general, what are possible advantages of one design over another? Class 27: Exam 2. Exam 2 Parenthesizing the Expression. Design A.

Menu. In general, what are possible advantages of one design over another? Class 27: Exam 2. Exam 2 Parenthesizing the Expression. Design A. cs2220: Engineering Software Class 27: Exam 2 Menu Exam 2 Parenthesizing the Expression Fall 2010 UVa David Evans Design A Design B In general, what are possible advantages of one design over another?

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Advanced Java Multithreading Techniques

Advanced Java Multithreading Techniques Advanced Java Multithreading Techniques Peter Haggar Senior Software Engineer IBM Corporation Research Triangle Park, NC haggar@us.ibm.com Peter Haggar Advanced Java Multithreading Techniques Page 1 About

More information

Concurrency WS 2010/2011 The Java Memory Model

Concurrency WS 2010/2011 The Java Memory Model Concurrency WS 2010/2011 The Java Memory Model Peter Thiemann November 2, 2010 Outline 1 Java Memory Model 2 Example Programs Java Memory Model Java does not guarantee linearizability or sequential consistency

More information

Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 2 Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5a due now You will get early feedback tomorrow! Thank your TAs 2nd

More information

Singleton. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 29

Singleton. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 29 Singleton Computer Science and Engineering College of Engineering The Ohio State University Lecture 29 Preventing Instantiation Default (zero-argument) constructor Provided only if there is no explicit

More information

The Java Memory Model

The Java Memory Model Jeremy Manson 1, William Pugh 1, and Sarita Adve 2 1 University of Maryland 2 University of Illinois at Urbana-Champaign Presented by John Fisher-Ogden November 22, 2005 Outline Introduction Sequential

More information

CS18000: Programming I

CS18000: Programming I CS18000: Programming I Synchronization 22 February, 2010 Prof. Chris Clifton Concurrency Example: Banking class ATM { public void withdrawcash(acct a) { Scanner sc = new Scanner(System.in); int amount

More information

Models of concurrency & synchronization algorithms

Models of concurrency & synchronization algorithms Models of concurrency & synchronization algorithms Lecture 3 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu

More information

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer. CMSC 330: Organization of Programming Languages Threads Computation Abstractions t1 t2 t1 t3 t2 t1 p1 p2 p3 p4 CPU 1 CPU 2 A computer t4 t5 Processes (e.g., JVM s) Threads CMSC 330 2 Processes vs. Threads

More information

SOLID + CleanCode. Design objektorientierter Systeme

SOLID + CleanCode. Design objektorientierter Systeme SOLID + CleanCode Design objektorientierter Systeme msg Monat 2016 Präsentationstitel 2 Style matters and there s beauty in simplicity. msg Monat 2016 Präsentationstitel 3 What should matter Clarity Brevity

More information

Domain-Driven Design Activity

Domain-Driven Design Activity Domain-Driven Design Activity SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester Institute of Technology Entities and Value Objects are special types of objects

More information

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

Enough java.lang.string to Hang Ourselves...

Enough java.lang.string to Hang Ourselves... Enough java.lang.string to Hang Ourselves... Dr Heinz M. Kabutz Last Updated 2018-06-19 2018 Heinz Kabutz, All Rights Reserved !2 Converting int val to a String? 1."" + val 2.Integer.toString(val) 3.Integer.valueOf(val)

More information

Java HashMap Interview Questions

Java HashMap Interview Questions Java HashMap Interview Questions codespaghetti.com/java-hashmap-interview-questions/ HashMap Java HashMap Interview Questions, Algorithms and Programs. Table of Contents: CHAPTER 1: Java HashMap Interview

More information

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 Learning from Bad Examples CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 1 Goals Demonstrate techniques to design for shared mutability Build on an example where multiple threads

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

Identity, State and Values

Identity, State and Values Identity, State and Values Clojure s approach to concurrency Rich Hickey Agenda Functions and processes Identity, State, and Values Persistent Data Structures Clojure s Managed References Q&A Functions

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Wait / Notify / NotifyAll Optimistic Retries Composition Follow-up (the risk I mentioned) ReentrantLock, Wait, Notify, NotifyAll Some

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

CS 1302 Chapter 9 (Review) Object & Classes

CS 1302 Chapter 9 (Review) Object & Classes CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

Problems with Concurrency

Problems with Concurrency with Concurrency February 14, 2012 1 / 27 s with concurrency race conditions deadlocks GUI source of s non-determinism deterministic execution model interleavings 2 / 27 General ideas Shared variable Shared

More information

Programmazione di sistemi multicore

Programmazione di sistemi multicore Programmazione di sistemi multicore A.A. 2015-2016 LECTURE 14 IRENE FINOCCHI http://wwwusers.di.uniroma1.it/~finocchi/ Programming with locks and critical sections MORE BAD INTERLEAVINGS GUIDELINES FOR

More information

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems Effective Concurrent Java Brian Goetz Sr. Staff Engineer, Sun Microsystems brian.goetz@sun.com The Big Picture Writing correct concurrent code is difficult, but not impossible. Using good object-oriented

More information

Lecture 7 Java SE Multithreading

Lecture 7 Java SE Multithreading Lecture 7 Java SE Multithreading presentation Java Programming Software App Development Cristian Toma D.I.C.E/D.E.I.C Department of Economic Informatics & Cybernetics www.dice.ase.ro Cristian Toma Business

More information

Question Points Score Total 100

Question Points Score Total 100 Midterm Exam #1 CMSC 433 Programming Language Technologies and Paradigms Spring 2011 March 3, 2011 Guidelines Put your name on each page before starting the exam. Write your answers directly on the exam

More information

Josh Bloch Charlie Garrod Darya Melicher

Josh Bloch Charlie Garrod Darya Melicher Principles of Software Construction: Objects, Design, and Concurrency Concurrency part 2 Synchronization, communication, and liveness Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Reading due

More information

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

Advanced MEIC. (Lesson #18)

Advanced MEIC. (Lesson #18) Advanced Programming @ MEIC (Lesson #18) Last class Data races Java Memory Model No out-of-thin-air values Data-race free programs behave as expected Today Finish with the Java Memory Model Introduction

More information