Lecture 17: Sharing Objects in Java

Size: px
Start display at page:

Download "Lecture 17: Sharing Objects in Java"

Transcription

1 COMP 150-CCP Concurrent Programming Lecture 17: Sharing Objects in Java Dr. Richard S. Hall Concurrent programming March 25, 2008

2 Reference The content of this lecture is based on Chapter 3 of the Java Concurrency in Practice book by Brian Goetz.

3 Sharing State Previously, we discussed how to prevent multiple threads from accessing shared state at the same time Now we examine techniques for sharing and publishing objects so they can be safely accessed by multiple threads These two issues provide the foundation for creating thread-safe classes and applications

4 Dual Roles of Synchronization The obvious role of synchronized in Java is for providing mutual exclusion It also plays a significant, but subtle role in memory visibility We not only want to prevent multiple threads from modifying the same state at the same time We also want to ensure that when one thread makes changes, that other threads see them

5 Visibility Example public class NoVisibility { private static boolean ready; private static int number; What is the result of executing this program? private static class ReaderThread extends Thread { public void run() { while (!ready) Thread.yield(); System.out.println(number); public static void main(string[] args) { new ReaderThread().start(); number = 42; ready = true;

6 Visibility Example public class NoVisibility { private static boolean ready; private static int number; It could output private static class ReaderThread extends Thread { public void run() { while (!ready) Thread.yield(); System.out.println(number); public static void main(string[] args) { new ReaderThread().start(); number = 42; ready = true;

7 Visibility Example public class NoVisibility { private static boolean ready; private static int number; Or output 0... private static class ReaderThread extends Thread { public void run() { while (!ready) Thread.yield(); System.out.println(number); public static void main(string[] args) { new ReaderThread().start(); number = 42; ready = true;

8 Visibility Example public class NoVisibility { private static boolean ready; private static int number; Or never exit at all. private static class ReaderThread extends Thread { public void run() { while (!ready) Thread.yield(); System.out.println(number); public static void main(string[] args) { new ReaderThread().start(); number = 42; ready = true;

9 Visibility Visibility is subtle because it is counterintuitive For example, you expect that writes should be visible to subsequent reads However, when reads and writes occur in different threads, this is simply not the case There is no guarantee that one thread will ever see the values written by another thread There is no guarantee that events will occur in a given order Why?

10 Visibility Visibility is subtle because it is counterintuitive For example, you expect that writes should be visible to subsequent reads However, when reads and writes occur in different threads, this is simply not the case There is no guarantee that one thread will ever see the values written by another thread There is no guarantee that events will occur in a given order Why? This allows compilers and JVM implementations to take advantage of multiprocessors to improve performance

11 Visibility Visibility issues can be very difficult to discover Inhibit our ability to reason about cause and effect Inhibit our ability to reason about ordering A solution is to always use proper synchronization whenever data is shared across threads Easier than it sounds

12 Visibility As the previous example shows, insufficient synchronization can result in stale data Threads may see out-of-date values unless synchronization is used whenever a variable is accessed Staleness is also not predictable or necessarily all-ornothing 64-bit operations on long or double variables may actually be broken into two 32-bit operations Stale data may result in serious safety or liveness issues Like the possibility that the previous example never exits

13 Visibility Example What can we say about this class? public class MutableInteger { private int value; public int get() { return value; public void set(int value) { this.value = value;

14 Visibility Example It is not thread safe. public class MutableInteger { private int value; public int get() { return value; public void set(int value) { this.value = value;

15 Visibility Example Is it thread safe now? public class MutableInteger { private int value; public int get() { return value; public synchronized void set(int value) { this.value = value;

16 Visibility Example public class MutableInteger { private int value; public synchronized int get() { return value; No. Both methods must be synchronized since they both provide access to the shared variable. public synchronized void set(int value) { this.value = value;

17 Locking and Visibility y = 1 lock M x = 1 unlock M Thread A Everything before the unlock on M......is visible to everything after the lock on M Thread B lock M i = x unlock M j = y

18 Locking and Visibility When thread A executes a synchronized block and subsequently thread B enters a synchronized block guarded by the same lock......then the values of variables that were visible to A prior to releasing the lock are guaranteed to be visible to B upon acquiring the lock i.e., everything A did in or prior to a synchronized block is visible to B when it executes a synchronized block guarded by the same lock Without synchronization, there is no such guarantee

19 Locking and Visibility When thread A executes a synchronized block and subsequently thread B enters a synchronized block guarded by the same lock......then the values of variables that were visible to A prior to releasing the lock are guaranteed to be visible to B upon acquiring the lock i.e., everything A did in or prior to a synchronized block is visible to B when it executes a synchronized block guarded by the same lock Without synchronization, there is no such guarantee This is also why access to shared state must be guarded by the same lock Protecting it with two different locks could result in seeing stale values

20 Locking and Visibility Summary: Locking is not just about mutual exclusion; it is also about memory visibility. To ensure that all threads see the most up-to-date values of shared mutable variables, the reading and writing threads must synchronize on a common lock.

21 Visibility Volatile variables A weaker form of synchronization, ensures that variable updates are propagated predictably Basically, volatile declaration puts compiler and runtime on notice that the variable is shared Thus, operations should not be reordered with other memory operations Additionally, volatile variables are not cached where their values may be hidden from other processors i.e., a read always returns the most recent value

22 Visibility Volatile variables A volatile int behaves similarly to: public class MutableInteger { private int value; public synchronized int get() { return value; Benefits? public synchronized void set(int value) { this.value = value;

23 Visibility Volatile variables A volatile int behaves similarly to: public class MutableInteger { private int value; public synchronized int get() { return value; Benefits? public synchronized void set(int value) { this.value = value; No locking, no blocking, so lighter weight Also extends visibility to all variables prior to writing/reading the volatile variable Thus, it is very similar to entering and leaving a synchronized block

24 Visibility Volatile variables However, the use of volatiles should be limited Code is more fragile and harder to understand than explicit locking Typical proper usage of volatile variables: volatile boolean stop = false;... while (!stop) { dosomething();... Often used for flags to signal life-cycle events

25 Visibility Example Volatile variables Countdown example from Magee & Kramer textbook: public class CountDown implements Runnable { private final static int N = 10; private Thread thread; public void start() { thread = new Thread(this); thread.start(); public void stop() { thread = null; public void run() { int i = N; while (i >= 0) { if (thread == null) return; else if (i == 0) Is this correct? System.out.println("beep"); else if (i > 0) tick(i); i--; private void tick(int i) { System.out.println("tick: " + i); try { Thread.sleep(1000); catch (InterruptedException ex) {

26 Visibility Example Volatile variables Countdown example from Magee & Kramer textbook: public class CountDown implements Runnable { private final static int N = 10; private Thread thread; public void start() { thread = new Thread(this); thread.start(); public void stop() { thread = null; public void run() { int i = N; while (i >= 0) { if (thread == null) return; else if (i == 0) System.out.println("beep"); else if (i > 0) tick(i); i--; No. The stop() method is used to signal count down thread. private void tick(int i) { System.out.println("tick: " + i); try { Thread.sleep(1000); catch (InterruptedException ex) {

27 Visibility Example Volatile variables Countdown example from Magee & Kramer textbook: public class CountDown implements Runnable { private final static int N = 10; private Thread thread; public void start() { thread = new Thread(this); thread.start(); public void stop() { thread = null; public void run() { int i = N; while (i >= 0) { if (thread == null) return; else if (i == 0) How do we fix it? System.out.println("beep"); else if (i > 0) tick(i); i--; private void tick(int i) { System.out.println("tick: " + i); try { Thread.sleep(1000); catch (InterruptedException ex) {

28 Visibility Example Volatile variables Countdown example from Magee & Kramer textbook: public class CountDown implements Runnable { private final static int N = 10; volatile private Thread thread; public void start() { thread = new Thread(this); thread.start(); public void stop() { thread = null; public void run() { int i = N; while (i >= 0) { if (thread == null) return; else if (i == 0) System.out.println("beep"); else if (i > 0) tick(i); i--; Make thread variable volatile. private void tick(int i) { System.out.println("tick: " + i); try { Thread.sleep(1000); catch (InterruptedException ex) {

29 Visibility Volatile variables Are convenient, but have limitations Locking guarantees both visibility and atomicity, but volatile variables guarantee only visibility For example, read-modify-write operations are not atomic, such as the increment operator (e.g., count++) For this, it is better to use atomic variables in java.util.concurrent, which provide read-modify-write methods

30 Visibility Volatile variables Are convenient, but have limitations Locking guarantees both visibility and atomicity, but volatile variables guarantee only visibility For example, read-modify-write operations are not atomic, such as the increment operator (e.g., count++) For this, it is better to use atomic variables in java.util.concurrent, which provide read-modify-write methods You can use volatile variables when Writes to the variable do not depend on its current value (or you can ensure that only a single thread updates its value),

31 Visibility Volatile variables Are convenient, but have limitations Locking guarantees both visibility and atomicity, but volatile variables guarantee only visibility For example, read-modify-write operations are not atomic, such as the increment operator (e.g., count++) For this, it is better to use atomic variables in java.util.concurrent, which provide read-modify-write methods You can use volatile variables when Writes to the variable do not depend on its current value (or you can ensure that only a single thread updates its value), The variable does not participate in invariants with other state variables, and

32 Visibility Volatile variables Are convenient, but have limitations Locking guarantees both visibility and atomicity, but volatile variables guarantee only visibility For example, read-modify-write operations are not atomic, such as the increment operator (e.g., count++) For this, it is better to use atomic variables in java.util.concurrent, which provide read-modify-write methods You can use volatile variables when Writes to the variable do not depend on its current value (or you can ensure that only a single thread updates its value), The variable does not participate in invariants with other state variables, and Locking is not required for any other reason while accessing the variable.

33 Object Publication You publish an object by making it available outside of its current scope e.g., storing a reference in a static variable, returning it from a method, or passing it to a method Must consider which objects you intend to publish and those which you do not Publishing objects unintentionally can compromise encapsulation, consistency, and thread safety If we want to publish objects we want to do so in a thread-safe way Objects published unintentionally are said to have escaped

34 Object Publication Example public static Set<Secret> knownsecrets; public void initialize() { knownsecrets = new HashSet<Secret>(); Public static references are the most direct way to publish an object...

35 Object Publication Example public static Set<Secret> knownsecrets; public void initialize() { knownsecrets = new HashSet<Secret>(); Also publishes any objects reachable from the published object.

36 Object Publication Example class UnsafeStates { private String[] states = new String[] { "AK", "AL"... ; public String[] getstates() { return states; Returning array references also publishes an object...

37 Object Publication Example class UnsafeStates { private String[] states = new String[] { "AK", "AL"... ; public String[] getstates() { return states; This is bad, since the returned array is mutable.

38 Object Publication Need to think explicitly about object publication Publishing an object indirectly publishes all objects reachable from the published object By following some chain of non-private field references and method calls This means that passing references to alien methods is potentially problematic for thread safety A method is alien to class C if it is not fully specified by C This includes methods of other classes as well as overrideable methods (i.e., non-private, non-final) You do not know how the alien code will use the reference

39 Object Publication Example public class Listen { public Listen(EventSource source) { source.registerlistener(new EventListener() { public void onevent(event e) { dosomething(e); ); This is a common event listener pattern in Java...

40 Object Publication Example public class Listen { public Listen(EventSource source) { source.registerlistener(new EventListener() { public void onevent(event e) { dosomething(e); ); This example lets this escape, since inner classes have an implicit reference to this.

41 Object Publication this escape is a special case of object escape Objects are not valid until after their constructor returns, so care must be take to not publish this in the constructor Use a static factory method to avoid this from escaping

42 Object Publication Example public class Listener { private final EventListener listener; private Listener() { listener = new EventListener() { public void onevent(event e) { dosomething(e); ; Perform initialization in static factory method. public static Listener newinstance(eventsource s) { Listener l = new Listener(); s.registerlistener(s.listener); return safe;

43 Thread Confinement One way to avoid concurrency issues is to avoid sharing data among threads If an object is confined to a single thread, then no synchronization is needed Swing uses thread confinement There is often no way to guarantee that an object is confined to a single thread, it is a matter of design Similar to guarding data with locks

44 Thread Confinement Ad-hoc thread confinement Thread confinement is based solely on proper implementation e.g., Swing Not really supported by language features Typically used to implement a single-threaded subsystem For simplicity To avoid deadlock Should be used sparingly, since there is no explicit enforcement

45 Thread Confinement Stack confinement Special case of thread confinement in which an object can only be reached through local variables Less fragile and simpler to maintain than ad-hoc confinement Quite easy for primitive types, but object references requires more effort i.e., no returning references We have seen this in some of our examples and exercises No interference is possible if we do not reference external entities

46 Thread Confinement ThreadLocal variables A special per thread object reference Has getter and setter methods to access an object reference Maintains a separate reference for each thread that uses it Used to prevent sharing of singletons or globals Can also be used to avoid passing a common argument to every method Also useful in cases where you want to have reusable buffers for some operation Widely used in Java EE containers to associate a transaction context with a given thread Easy to abuse by using too many for globals or hidden method arguments Use with care

47 Thread Confinement ThreadLocal example private static ThreadLocal<Connection> connectionholder = new ThreadLocal<Connection>() { public Connection initialvalue() { return DriverManager.getConnection(DB_URL); ; public static Connection getconnection() { return connectionholder.get(); Allows each thread to have its a non-shared database connection...

48 Thread Confinement ThreadLocal example private static ThreadLocal<Connection> connectionholder = new ThreadLocal<Connection>() { public Connection initialvalue() { return DriverManager.getConnection(DB_URL); ; public static Connection getconnection() { return connectionholder.get(); They automatically get their own copy when calling getconnection().

49 Immutability Another way to avoid concurrency issues is to avoid using mutable state An immutable object is one whose state cannot be changed after construction Immutable objects are always thread safe

50 Immutability Another way to avoid concurrency issues is to avoid using mutable state An immutable object is one whose state cannot be changed after construction Immutable objects are always thread safe An object is immutable if Its state cannot be modified after construction, All its fields are final, and It is properly constructed (i.e., this does not escape during construction) Simpler to reasonable about object state Safer to pass to untrusted code

51 Immutability final fields Limited form of C++ const Final fields cannot be modified after initialization Also have special semantics in Java memory model It is good practice to make all fields final unless they explicitly need to be mutable

52 Immutable Example public final class ThreeStooges { private final Set<String> stooges = new HashSet<String>(); public ThreeStooges() { stooges.add("moe"); stooges.add("larry"); stooges.add("curly"); public boolean isstooge(string name) { return stooges.contains(name); Is this class immutable?

53 Immutable Example public final class ThreeStooges { private final Set<String> stooges = new HashSet<String>(); public ThreeStooges() { stooges.add("moe"); stooges.add("larry"); stooges.add("curly"); public boolean isstooge(string name) { return stooges.contains(name); Yes. You can use mutable classes as long as they don't escape and the values don't change.

54 Immutability How useful are immutable objects if their state cannot change?

55 Immutability How useful are immutable objects if their state cannot change? It is still possible to update program state by replacing immutable objects with new instances Example...

56 Immutable Example Recall our unsafe caching factorizer public class CachingFactorizer implements Servlet { private final AtomicReference<BigInteger> lastnumber = new AtomicReference<BigInteger>(); private final AtomicReference<BigInteger[]> lastfactors = new AtomicReference<BigInteger[]>(); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); if (i.equals(lastnumber.get())) encodeintoresponse(resp, lastfactors.get()); else { BigInteger[] factors = factor(i); lastnumber.set(i); lastfactors.set(factors); encodeintoresponse(resp, factors); What was the issue here?

57 Immutable Example Recall our unsafe caching factorizer public class CachingFactorizer implements Servlet { private final AtomicReference<BigInteger> lastnumber = new AtomicReference<BigInteger>(); private final AtomicReference<BigInteger[]> lastfactors = new AtomicReference<BigInteger[]>(); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); if (i.equals(lastnumber.get())) encodeintoresponse(resp, lastfactors.get()); else { BigInteger[] factors = factor(i); lastnumber.set(i); lastfactors.set(factors); encodeintoresponse(resp, factors); The two state values were dependent on each other, but not atomic.

58 Immutable Example Recall our unsafe caching factorizer public class CachingFactorizer implements Servlet { private final AtomicReference<BigInteger> lastnumber = new AtomicReference<BigInteger>(); private final AtomicReference<BigInteger[]> lastfactors = new AtomicReference<BigInteger[]>(); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); if (i.equals(lastnumber.get())) encodeintoresponse(resp, lastfactors.get()); else { BigInteger[] factors = factor(i); lastnumber.set(i); lastfactors.set(factors); encodeintoresponse(resp, factors); So how could immutable objects help us here?

59 Immutable Example Consider this immutable object definition class OneValueCache { private final BigInteger lastnumber; private final BigInteger[] lastfactors; public OneValueCache(BigInteger i, BigInteger[] factors) { lastnumber = i; lastfactors = Arrays.copyOf(factors, factors.length); public BigInteger[] getfactors(biginteger i) { if (lastnumber == null!lastnumber.equals(i)) return null; else return Arrays.copyOf(lastFactors, lastfactors.length); This immutable object holds two values.

60 Immutable Example Consider this immutable object definition class OneValueCache { private final BigInteger lastnumber; private final BigInteger[] lastfactors; public OneValueCache(BigInteger i, BigInteger[] factors) { lastnumber = i; lastfactors = Arrays.copyOf(factors, factors.length); public BigInteger[] getfactors(biginteger i) { if (lastnumber == null Why not!lastnumber.equals(i)) just use the array directly... return null; else return Arrays.copyOf(lastFactors, lastfactors.length);

61 Immutable Example Consider this immutable object definition class OneValueCache { private final BigInteger lastnumber; private final BigInteger[] lastfactors; public OneValueCache(BigInteger i, BigInteger[] factors) { lastnumber = i; lastfactors = Arrays.copyOf(factors, factors.length); public BigInteger[] getfactors(biginteger i) { if (lastnumber == null!lastnumber.equals(i)) return null; else return Arrays.copyOf(lastFactors, lastfactors.length);...or return the array directly?

62 Immutable Example Consider this immutable object definition class OneValueCache { private final BigInteger lastnumber; private final BigInteger[] lastfactors; public OneValueCache(BigInteger i, BigInteger[] factors) { lastnumber = i; lastfactors = Arrays.copyOf(factors, factors.length); public BigInteger[] getfactors(biginteger i) { if (lastnumber == null!lastnumber.equals(i)) return null; else return Arrays.copyOf(lastFactors, lastfactors.length); It would allow the reference to escape.

63 Immutable Example Consider this immutable object definition class OneValueCache { private final BigInteger lastnumber; private final BigInteger[] lastfactors; public OneValueCache(BigInteger i, BigInteger[] factors) { lastnumber = i; lastfactors = Arrays.copyOf(factors, factors.length); public BigInteger[] getfactors(biginteger i) { if (lastnumber == null!lastnumber.equals(i)) return null; else return Arrays.copyOf(lastFactors, lastfactors.length); Ok, so how does this help?

64 Immutable Example Consider this new caching factorizer Is this now thread safe? public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

65 Immutable Example Consider this new caching factorizer Yes, and no locking. public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

66 Immutable Example Consider this new caching factorizer Why use volatile? public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

67 Immutable Example Consider this new caching factorizer Because each thread needs to see the most upto-date value. public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

68 Immutable Example Consider this new caching factorizer What happens if cache was accessed more than once? public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

69 Immutable Example Consider this new caching factorizer It would no longer be thread safe... public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

70 Immutable Example Consider this new caching factorizer You could use stack confinement to save a copy of cache. public class CachingFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(servletrequest req, ServletResponse resp) { BigInteger i = extractfromrequest(req); BigInteger[] factors = cache.getfactors(i); if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); encodeintoresponse(resp, factors);

71 Safe Publication So, how do we safely publish objects for sharing across threads? Consider an example...

72 Safe Publication Example A simple class to hold an integer value public class Holder { private int n; public Holder(int n) { this.n = n; public void assertsanity() { if (n!= n) throw new AssertionError( "This statement is false.");

73 Safe Publication Example Some class declares a public holder and initializes it public Holder holder; public void initialize() { holder = new Holder(42); Will this work?

74 Safe Publication Example Some class declares a public holder and initializes it public Holder holder; public void initialize() { holder = new Holder(42); Not necessarily. It could be possible for a thread to see holder in a partially constructed state.

75 Safe Publication Example Some class declares a public holder and initializes it public Holder holder; public void initialize() { holder = new Holder(42); Since synchronization was not used to make the Holder instance visible, it is not properly published.

76 Safe Publication Improperly published objects could result in Other threads seeing a stale value for the reference itself (i.e, holder in the example) Other threads could see stale state values inside the referenced object (i.e., inside holder in the example) Other threads may see state values change in unpredictable ways

77 Immutability and Safe Publication Typically, synchronization is needed for safe publication of objects However, immutable objects have a guarantee of initialization safety in the Java memory model Requirements of immutability must be met (i.e., unmodifiable state, all fields final, and proper construction) Immutable objects can be safely published even without synchronization

78 Safe Publication Idioms Mutable objects must be safely published i.e., the reference to the object and the object's state must be made visible to other threads at the same time

79 Safe Publication Idioms Mutable objects must be safely published i.e., the reference to the object and the object's state must be made visible to other threads at the same time Safe publication of a properly constructed object can be accomplished by Initializing an object reference from a static initializer,

80 Safe Publication Idioms Mutable objects must be safely published i.e., the reference to the object and the object's state must be made visible to other threads at the same time Safe publication of a properly constructed object can be accomplished by Initializing an object reference from a static initializer, Storing a reference to it in a volatile field,

81 Safe Publication Idioms Mutable objects must be safely published i.e., the reference to the object and the object's state must be made visible to other threads at the same time Safe publication of a properly constructed object can be accomplished by Initializing an object reference from a static initializer, Storing a reference to it in a volatile field, Storing a reference to it into a final field of a properly constructed object, or

82 Safe Publication Idioms Mutable objects must be safely published i.e., the reference to the object and the object's state must be made visible to other threads at the same time Safe publication of a properly constructed object can be accomplished by Initializing an object reference from a static initializer, Storing a reference to it in a volatile field, Storing a reference to it into a final field of a properly constructed object, or Storing a reference to it into a field that is properly guarded by a lock

83 Safe Publication Idioms Sounds difficult, doesn't it?

84 Safe Publication Idioms Sounds difficult, doesn't it? It is difficult and care is needed, but in practice it can be simplified to some degree For example, using thread-safe collection classes makes it possible to safely publish objects without explicit synchronization in the threads

85 Safe Publication Summary The publication requirements for an object depend on its mutability

86 Safe Publication Summary The publication requirements for an object depend on its mutability Immutable objects can be published through any mechanism

87 Safe Publication Summary The publication requirements for an object depend on its mutability Immutable objects can be published through any mechanism Effectively immutable objects must be safely published

88 Safe Publication Summary The publication requirements for an object depend on its mutability Immutable objects can be published through any mechanism Effectively immutable objects must be safely published Mutable objects must be safely published and must be either thread-safe or guarded by a lock

Sharing Objects. Java and Android Concurrency.

Sharing Objects. Java and Android Concurrency. Java and Android Concurrency Sharing Objects fausto.spoto@univr.it git@bitbucket.org:spoto/java-and-android-concurrency.git git@bitbucket.org:spoto/java-and-android-concurrency-examples.git Fausto Spoto

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

Lecture 16: Thread Safety in Java

Lecture 16: Thread Safety in Java COMP 150-CCP Concurrent Programming Lecture 16: Thread Safety in Java Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming March 13, 2008 Reference The content of this lecture is based on Chapter

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

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

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

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

Design Patterns & Concurrency. Sebastian Graf, Oliver Haase

Design Patterns & Concurrency. Sebastian Graf, Oliver Haase Design Patterns & Concurrency Sebastian Graf, Oliver Haase 1 Fundamentals 2 Recap Threadsafety What is threadsafety? How can threadsafety be ensured? Amdahls Law 3 Recap Threadsafety public final class

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 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 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

Lecture 9: Introduction to Monitors

Lecture 9: Introduction to Monitors COMP 150-CCP Concurrent Programming Lecture 9: Introduction to Monitors Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 14, 2008 Abstracting Locking Details Recall our discussion

More information

CMSC 433 Programming Language Technologies and Paradigms. Synchronization

CMSC 433 Programming Language Technologies and Paradigms. Synchronization CMSC 433 Programming Language Technologies and Paradigms Synchronization Aspects of Synchronization Atomicity Locking to obtain mutual exclusion What we most often think about Visibility Ensuring that

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

System Programming. Practical Session 4: Threads and Concurrency / Safety

System Programming. Practical Session 4: Threads and Concurrency / Safety System Programming Practical Session 4: Threads and Concurrency / Safety Using Threads - All the computer programs you've seen so far were sequential only one thing was performed at any given time - Sometimes

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

Synchronization SPL/2010 SPL/20 1

Synchronization SPL/2010 SPL/20 1 Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization

More information

Safety SPL/2010 SPL/20 1

Safety SPL/2010 SPL/20 1 Safety 1 system designing for concurrent execution environments system: collection of objects and their interactions system properties: Safety - nothing bad ever happens Liveness - anything ever happens

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

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

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

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Concurrency in Object Oriented Programs 1 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Concurrency: the Future of Computing Java Concurrency Thread Safety

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

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

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

Lecture 32: Volatile variables, Java memory model

Lecture 32: Volatile variables, Java memory model COMP 322: Fundamentals of Parallel Programming Lecture 32: Volatile variables, Java memory model Vivek Sarkar Department of Computer Science, Rice University vsarkar@rice.edu https://wiki.rice.edu/confluence/display/parprog/comp322

More information

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

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

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

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

COMP 150-CCP Concurrent Programming. Lecture 12: Deadlock. Dr. Richard S. Hall

COMP 150-CCP Concurrent Programming. Lecture 12: Deadlock. Dr. Richard S. Hall COMP 150-CCP Concurrent Programming Lecture 12: Deadlock Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 28, 2008 Scenario Process 1 gets the lock for object A and wants to lock

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

COMP 322: Fundamentals of Parallel Programming

COMP 322: Fundamentals of Parallel Programming COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 28: Java Threads (contd), synchronized statement Vivek Sarkar Department of Computer Science

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

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

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

Lecture 10: Introduction to Semaphores

Lecture 10: Introduction to Semaphores COMP 150-CCP Concurrent Programming Lecture 10: Introduction to Semaphores Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 19, 2008 Semaphores Semaphores (Dijkstra 1968) are widely

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

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

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

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

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2) Network Programming COSC 1176/1179 Lecture 6 Concurrent Programming (2) Threads Recall from last week Every line of Java code is part of a thread There can be one or more threads running in parallel Each

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

Multiple Inheritance. Computer object can be viewed as

Multiple Inheritance. Computer object can be viewed as Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.

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

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

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

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

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

Atropos User s manual

Atropos User s manual Atropos User s manual Jan Lönnberg 22nd November 2010 1 Introduction Atropos is a visualisation tool intended to display information relevant to understanding the behaviour of concurrent Java programs,

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

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Threads block when they can t get that lock Wanna have your threads stall? Go ahead, synchronize it all The antidote to this liveness pitfall? Keeping

More information

Lecture 19: Composing Objects in Java

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

More information

Audience. Revising the Java Thread/Memory Model. Java Thread Specification. Revising the Thread Spec. Proposed Changes. When s the JSR?

Audience. Revising the Java Thread/Memory Model. Java Thread Specification. Revising the Thread Spec. Proposed Changes. When s the JSR? Audience Revising the Java Thread/Memory Model See http://www.cs.umd.edu/~pugh/java/memorymodel for more information 1 This will be an advanced talk Helpful if you ve been aware of the discussion, have

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

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data Lecture 4 Monitors Summary Semaphores Good news Simple, efficient, expressive Passing the Baton any await statement Bad news Low level, unstructured omit a V: deadlock omit a P: failure of mutex Synchronisation

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

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

Java Platform Concurrency Gotchas

Java Platform Concurrency Gotchas Java Platform Concurrency Gotchas Alex Miller Terracotta Questions to answer > What are common concurrency problems? > Why are they problems? > How do I detect these problems? > How do I correct these

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

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify http://cs.lth.se/eda040 Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify Klas Nilsson 2016-09-20 http://cs.lth.se/eda040 F4: Monitors: synchronized, wait and

More information

Introduction to Locks. Intrinsic Locks

Introduction to Locks. Intrinsic Locks CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Introduction to Locks Intrinsic Locks Atomic-looking operations Resources created for sequential code make certain assumptions, a large

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

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

Threads, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

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

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Virtual Machine Design

Virtual Machine Design Virtual Machine Design Lecture 4: Multithreading and Synchronization Antero Taivalsaari September 2003 Session #2026: J2MEPlatform, Connected Limited Device Configuration (CLDC) Lecture Goals Give an overview

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

Concurrent Programming Lecture 10

Concurrent Programming Lecture 10 Concurrent Programming Lecture 10 25th September 2003 Monitors & P/V Notion of a process being not runnable : implicit in much of what we have said about P/V and monitors is the notion that a process may

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

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

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 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

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

What is a thread anyway?

What is a thread anyway? Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

Classes Classes 2 / 36

Classes Classes 2 / 36 Classes 1 / 36 Classes Classes 2 / 36 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

Chapter 4: Writing Classes

Chapter 4: Writing Classes Chapter 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Writing Classes We've been using predefined classes. Now we will learn to write our own

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

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

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 341, Autumn 2015, Ruby Introduction Summary CSE 341, Autumn 2015, Ruby Introduction Summary Disclaimer: This lecture summary is not necessarily a complete substitute for atting class, reading the associated code, etc. It is designed to be a useful

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11: Semaphores I" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" problems with Peterson s algorithm semaphores implementing semaphores

More information

Lecture 03: Thread API (continue)

Lecture 03: Thread API (continue) Lecture 03: Thread API (continue) SSC2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Lecture 03 1 Recap Extending Thread or implementing Runnable Thread terminology Stopping Threads

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

Programming Language Concepts: Lecture 11

Programming Language Concepts: Lecture 11 Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]

More information

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

Shared-Memory and Multithread Programming

Shared-Memory and Multithread Programming Shared-Memory and Multithread Programming Pruet Boonma pruet@eng.cmu.ac.th Department of Computer Engineering Faculty of Engineering, Chiang Mai University Based on a material by: Bryan Carpenter Pervasive

More information

Lecture 29: Java s synchronized statement

Lecture 29: Java s synchronized statement COMP 322: Fundamentals of Parallel Programming Lecture 29: Java s synchronized statement Vivek Sarkar Department of Computer Science, Rice University vsarkar@rice.edu https://wiki.rice.edu/confluence/display/parprog/comp322

More information

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax Lab report Project 3 Mihai Ene I have implemented the solution in Java. I have leveraged its threading mechanisms and concurrent API (i.e. concurrent package) in order to achieve the required functionality

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

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information