Lecture 19: Composing Objects in Java

Size: px
Start display at page:

Download "Lecture 19: Composing Objects in Java"

Transcription

1 COMP 150-CCP Concurrent Programming Lecture 19: Composing Objects in Java Dr. Richard S. Hall Concurrent programming April 1, 2008

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

3 Raising the Level The last few lectures have focused on low-level details of the Java memory model i.e., memory visibility guarantees It is important to understand these details to understand the issues However, these issues are somewhat overwhelming As mentioned in the last lecture, these issues can be simplified by using existing classes and/or various approaches This lecture will focus on how to structure classes to ensure their thread safety

4 Designing a Thread-Safe Class The design process for a thread-safe class should include these three basic elements

5 Designing a Thread-Safe Class The design process for a thread-safe class should include these three basic elements Identify the variables that form the object's state,

6 Designing a Thread-Safe Class The design process for a thread-safe class should include these three basic elements Identify the variables that form the object's state, Identify the invariants that constrain the state variables, and

7 Designing a Thread-Safe Class The design process for a thread-safe class should include these three basic elements Identify the variables that form the object's state, Identify the invariants that constrain the state variables, and Establish a policy for managing concurrent access to the object's state Encapsulation of state plays a key role

8 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; this.y = y; public int getx() { return x; public void setx(int x) { this.x = x; public int gety() { return y; public void sety(int y) { this.y = y;

9 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; What is the state of this this.y = y; class? public int getx() { return x; public void setx(int x) { this.x = x; public int gety() { return y; public void sety(int y) { this.y = y;

10 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; this.y = y; public int getx() { return x; public void setx(int x) { this.x = x; public int gety() { return y; public void sety(int y) { this.y = y; The x and y member fields.

11 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; this.y = y; public int getx() { return x; public void setx(int x) { this.x = x; public int gety() { return y; public void sety(int y) { this.y = y; Which invariants constrain the state?

12 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; this.y = y; public int getx() { return x; public void setx(int x) { this.x = x; public int gety() { return y; public void sety(int y) { this.y = y; Difficult to say, but looking at this none, since there isn't an obvious relationship between x and y.

13 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; So, how should we protect the state? this.y = y; public int getx() { return x; public void setx(int x) { this.x = x; public int gety() { return y; public void sety(int y) { this.y = y;

14 Determining Object State Consider the following class: public class Point { private int x, y; public Point(x, y) { this.x = x; Synchronize the state access methods. this.y = y; public synchronized int getx() { return x; public synchronized void setx(int x) { this.x = x; public synchronized int gety() { return y; public synchronized void sety(int y) { this.y = y;

15 Object State Constraints Object state values may have certain constraints or invariants placed on them, e.g., Multiple related variables must be changed together Certain state values may be invalid Certain state transitions may be invalid

16 Object State Constraints Object state values may have certain constraints or invariants placed on them, e.g., Multiple related variables must be changed together Certain state values may be invalid Certain state transitions may be invalid These types of constraints put additional synchronization and encapsulation requirements Depending on the constraints, the level of encapsulation can be adjusted You cannot ensure thread safety without understanding an object's invariants and postconditions

17 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

18 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; What is the state? public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

19 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; The lower and upper fields. public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

20 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; Is the state properly protected? public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

21 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; Essentially, but what is wrong with this approach? public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

22 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; First, it has implicit protocol when changing both values to avoid an exception. public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

23 Object State Constraints Consider the following class: public class NumberRange { // INVARIANT: lower <= upper private long lower, upper; Even worse, another thread could be changing both values and we could interleave our values. public synchronized void setlower(int i) { if (i > upper) throw new IllegalArgumentException( Invalid ); lower.set(i); public synchronized void setupper(int i) { if (i < lower) throw new IllegalArgumentException( Invalid ); upper.set(i); public synchronized boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

24 State Ownership Java's garbage collection allows us to be lazy about state ownership This is considerably different in C++, for example

25 State Ownership Java's garbage collection allows us to be lazy about state ownership This is considerably different in C++, for example State ownership is not embodied in the language It is an element of class design

26 State Ownership Java's garbage collection allows us to be lazy about state ownership This is considerably different in C++, for example State ownership is not embodied in the language It is an element of class design When you pass a reference into a method are you Transferring ownership? Engaging in a short-term loan? Joining a long-term joint ownership? Often ownership and encapsulation go hand-inhand, but not necessarily

27 State Ownership The owner of state gets to determine the locking protocol used to maintain integrity Ownership implies control, which is why we have to be careful about unintentionally publishing objects Despite garbage collection, it is import to think carefully and be explicit about ownership Forms of split ownership are also common Collection classes maintain a set of objects that are ultimately owned by client code Who provides the locking protocol in this case?

28 Using Non-Thread-Safe Classes Consider the following class: public class PersonSet private final Set<Person> myset = new HashSet<Person>(); public synchronized void addperson(person p) { myset.add(p); public synchronized boolean containsperson(person p) { return myset.contains(p);

29 Using Non-Thread-Safe Classes Consider the following class: HashSet is not thread safe, is PersonSet thread safe? public class PersonSet private final Set<Person> myset = new HashSet<Person>(); public synchronized void addperson(person p) { myset.add(p); public synchronized boolean containsperson(person p) { return myset.contains(p);

30 Using Non-Thread-Safe Classes Consider the following class: Yes, because all access to the HashSet is properly guarded. public class PersonSet private final Set<Person> myset = new HashSet<Person>(); public synchronized void addperson(person p) { myset.add(p); public synchronized boolean containsperson(person p) { return myset.contains(p);

31 Using Non-Thread-Safe Classes Consider the following class: What about Person objects? public class PersonSet private final Set<Person> myset = new HashSet<Person>(); public synchronized void addperson(person p) { myset.add(p); public synchronized boolean containsperson(person p) { return myset.contains(p);

32 Using Non-Thread-Safe Classes Consider the following class: If they are mutable then they will need to be thread safe too, but depends on ownership. public class PersonSet private final Set<Person> myset = new HashSet<Person>(); public synchronized void addperson(person p) { myset.add(p); public synchronized boolean containsperson(person p) { return myset.contains(p);

33 Instance Confinement Encapsulation simplifies making classes thread safe by promoting instance confinement Confines access, which makes it easier to ensure proper locking policy Simplest way to use non-thread-safe classes with multiple threads Important to not let confined instance escape Approach common in JRE e.g., Collections.synchronizedList uses Decorator pattern to confine ArrayList Wraps each method as synchronized and delegates to the confined instance

34 Java Monitor Pattern Instance confinement taken to the extreme leads to the Java monitor pattern Object encapsulates all mutable state and guards it with its intrinsic lock The primary benefit is simplicity Using object's intrinsic lock is just convention Any lock would suffice

35 Java Monitor Pattern Example Consider the following example: public class PrivateLock { private final Object mylock = new Widget widget; void somemethod() { synchronized(mylock) { // Access or modify the state of widget

36 Java Monitor Pattern Example Consider the following example: Is this class a proper monitor? public class PrivateLock { private final Object mylock = new Widget widget; void somemethod() { synchronized(mylock) { // Access or modify the state of widget

37 Java Monitor Pattern Example Consider the following example: Yes. Why might you want to use a private lock instead of the intrinsic lock? public class PrivateLock { private final Object mylock = new Widget widget; void somemethod() { synchronized(mylock) { // Access or modify the state of widget

38 Java Monitor Pattern Example Consider the following example: Disallows client code from participating in the synchronization policy. public class PrivateLock { private final Object mylock = new Widget widget; void somemethod() { synchronized(mylock) { // Access or modify the state of widget

39 Vehicle Tracker Example 1 Consider a vehicle tracking system where we want to be able to get vehicles positions in the rendering thread, such as Map<String, Point> locations = vehicles.getlocations(); for (String key : locations.keyset()) rendervehicle(key, locations.get(key));

40 Vehicle Tracker Example 1 Consider a vehicle tracking system where we want to be able to get vehicles positions in the rendering thread, such as Map<String, Point> locations = vehicles.getlocations(); for (String key : locations.keyset()) rendervehicle(key, locations.get(key)); And we have an updater thread that updates vehicle locations, such as void vehiclemoved(vehiclemovedevent evt) { Point loc = evt.getnewlocation(); vehicles.setlocation(evt.getvehicleid(), loc.x, loc.y);

41 Vehicle Tracker Example 1 We use the following mutable point class: public class MutablePoint { public int x, y; public MutablePoint() { x = 0; y = 0; public MutablePoint(MutablePoint p) { this.x = p.x; this.y = p.y;

42 Vehicle Tracker Example 1 Vehicle tracker class (1/2): public class MonitorVehicleTracker private final Map<String, MutablePoint> locations; public MonitorVehicleTracker(Map<String, MutablePoint> locations) { this.locations = deepcopy(locations); public synchronized Map<String, MutablePoint> getlocations() { return deepcopy(locations); public synchronized MutablePoint getlocation(string id) { MutablePoint loc = locations.get(id); return loc == null? null : new MutablePoint(loc); // Continued...

43 Vehicle Tracker Example 1 Vehicle tracker class (2/2): public synchronized void setlocation(string id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) throw new IllegalArgumentException("No such ID: " + id); loc.x = x; loc.y = y; private static Map<String, MutablePoint> deepcopy( Map<String, MutablePoint> m) { Map<String, MutablePoint> result = new HashMap<String, MutablePoint>(); for (String id : m.keyset()) result.put(id, new MutablePoint(m.get(id))); return Collections.unmodifiableMap(result);

44 Vehicle Tracker Example 1 Vehicle tracker class (2/2): public synchronized void setlocation(string id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) throw new IllegalArgumentException("No such ID: " + id); loc.x = x; loc.y = y; private static Map<String, MutablePoint> deepcopy( Map<String, MutablePoint> m) { Map<String, MutablePoint> result = new HashMap<String, MutablePoint>(); for (String id : m.keyset()) result.put(id, new MutablePoint(m.get(id))); return Collections.unmodifiableMap(result); How did this implementation achieve thread safety?

45 Vehicle Tracker Example 1 Vehicle tracker class (2/2): public synchronized void setlocation(string id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) throw new IllegalArgumentException("No such ID: " + id); loc.x = x; loc.y = y; private static Map<String, MutablePoint> deepcopy( Map<String, MutablePoint> m) { Map<String, MutablePoint> result = new HashMap<String, MutablePoint>(); for (String id : m.keyset()) result.put(id, new MutablePoint(m.get(id))); return Collections.unmodifiableMap(result); By only returning copies of the mutable points.

46 Vehicle Tracker Example 1 Vehicle tracker class (2/2): public synchronized void setlocation(string id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) throw new IllegalArgumentException("No such ID: " + id); loc.x = x; loc.y = y; private static Map<String, MutablePoint> deepcopy( Map<String, MutablePoint> m) { Map<String, MutablePoint> result = new HashMap<String, MutablePoint>(); for (String id : m.keyset()) result.put(id, new MutablePoint(m.get(id))); return Collections.unmodifiableMap(result); What are some consequences of returning copies?

47 Vehicle Tracker Example 1 Vehicle tracker class (2/2): public synchronized void setlocation(string id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) throw new IllegalArgumentException("No such ID: " + id); loc.x = x; loc.y = y; private static Map<String, MutablePoint> deepcopy( Map<String, MutablePoint> m) { Map<String, MutablePoint> result = new HashMap<String, MutablePoint>(); for (String id : m.keyset()) result.put(id, new MutablePoint(m.get(id))); return Collections.unmodifiableMap(result); Potentially poorer performance...

48 Vehicle Tracker Example 1 Vehicle tracker class (2/2): public synchronized void setlocation(string id, int x, int y) { MutablePoint loc = locations.get(id); if (loc == null) throw new IllegalArgumentException("No such ID: " + id); loc.x = x; loc.y = y; private static Map<String, MutablePoint> deepcopy( Map<String, MutablePoint> m) { Map<String, MutablePoint> result = new HashMap<String, MutablePoint>(); for (String id : m.keyset()) result.put(id, new MutablePoint(m.get(id))); return Collections.unmodifiableMap(result); Also, returned information is potentially stale.

49 Delegating Thread Safety The Java monitor pattern is mostly useful useful for building thread-safe classes from scratch or to encapsulate non-thread-safe classes What happens if we are composing a class out of classes that are already thread safe? Do we need an additional layer of thread safety?

50 Delegating Thread Safety The Java monitor pattern is mostly useful useful for building thread-safe classes from scratch or to encapsulate non-thread-safe classes What happens if we are composing a class out of classes that are already thread safe? Do we need an additional layer of thread safety? Unfortunately, it depends We have seen examples where we do not, e.g, the counting factorizer using an AtomicLong We have seen example where we do, e.g., the caching factorizer using AtomicReferences

51 Vehicle Tracker Example 2 Assume we use this immutable public class Point { public final int x, y; public Point(int x, int y) { this.x = x; this.y = y;

52 Vehicle Tracker Example 2 New vehicle tracker class: public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiablemap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<String, Point>(points); unmodifiablemap = Collections.unmodifiableMap(locations); public Map<String, Point> getlocations() { return unmodifiablemap; public Point getlocation(string id) { return locations.get(id); public void setlocation(string id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) throw new IllegalArgumentException("invalid id: " + id);

53 Vehicle Tracker Example 2 New vehicle tracker class: public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiablemap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<String, Point>(points); unmodifiablemap = Collections.unmodifiableMap(locations); public Map<String, Point> getlocations() { return unmodifiablemap; public Point getlocation(string id) { return locations.get(id); Is this thread safe? public void setlocation(string id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) throw new IllegalArgumentException("invalid id: " + id);

54 Vehicle Tracker Example 2 New vehicle tracker class: public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiablemap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<String, Point>(points); unmodifiablemap = Collections.unmodifiableMap(locations); public Map<String, Point> getlocations() { return unmodifiablemap; public Point getlocation(string id) { return locations.get(id); Yes, it delegates to its thread-safe state and has no explicit synchronization. public void setlocation(string id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) throw new IllegalArgumentException("invalid id: " + id);

55 Vehicle Tracker Example 2 New vehicle tracker class: public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiablemap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<String, Point>(points); unmodifiablemap = Collections.unmodifiableMap(locations); public Map<String, Point> getlocations() { return unmodifiablemap; public Point getlocation(string id) { return locations.get(id); Is the behavior the same as the last version? public void setlocation(string id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) throw new IllegalArgumentException("invalid id: " + id);

56 Vehicle Tracker Example 2 New vehicle tracker class: public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiablemap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<String, Point>(points); unmodifiablemap = Collections.unmodifiableMap(locations); public Map<String, Point> getlocations() { return unmodifiablemap; public Point getlocation(string id) { return locations.get(id); No, it returns a live view, rather than a snapshot. public void setlocation(string id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) throw new IllegalArgumentException("invalid id: " + id);

57 Delegating Thread Safety The previous example only had a single state variable, so it was easy to delegate thread safety It is possible to delegate thread safety to multiple state variables, but they must be independent No invariants expressed across multiple variables

58 Delegating Thread Safety Example Consider the following example public class VisualComponent { private final List<KeyListener> keylisteners = new CopyOnWriteArrayList<KeyListener>(); private final List<MouseListener> mouselisteners = new CopyOnWriteArrayList<MouseListener>(); public void addkeylistener(keylistener listener) { keylisteners.add(listener); public void addmouselistener(mouselistener listener) { mouselisteners.add(listener); public void removekeylistener(keylistener listener) { keylisteners.remove(listener); public void removemouselistener(mouselistener listener) { mouselisteners.remove(listener);

59 Delegating Thread Safety Example Consider the following example public class VisualComponent { private final List<KeyListener> keylisteners = new CopyOnWriteArrayList<KeyListener>(); private final List<MouseListener> mouselisteners = new CopyOnWriteArrayList<MouseListener>(); public void addkeylistener(keylistener listener) { keylisteners.add(listener); This is thread safe because the state variables are independent. public void addmouselistener(mouselistener listener) { mouselisteners.add(listener); public void removekeylistener(keylistener listener) { keylisteners.remove(listener); public void removemouselistener(mouselistener listener) { mouselisteners.remove(listener);

60 Delegating Thread Safety Example What about our number range example? public class NumberRange { // INVARIANT: lower <= upper private final AtomicInteger lower = new AtomicInteger(0); private final AtomicInteger upper = new AtomicInteger(0); public void setlower(int i) { if (i > upper.get()) throw new IllegalArgumentException( "can't set lower to " + i + " > upper"); lower.set(i); public void setupper(int i) { if (i < lower.get()) throw new IllegalArgumentException( "can't set upper to " + i + " < lower"); upper.set(i); public boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get());

61 Delegating Thread Safety Example What about our number range example? public class NumberRange { // INVARIANT: lower <= upper private final AtomicInteger lower = new AtomicInteger(0); private final AtomicInteger upper = new AtomicInteger(0); public void setlower(int i) { if (i > upper.get()) throw new IllegalArgumentException( "can't set lower to " + i + " > upper"); lower.set(i); public void setupper(int i) { if (i < lower.get()) throw new IllegalArgumentException( "can't set upper to " + i + " < lower"); upper.set(i); public boolean isinrange(int i) { return (i >= lower.get() && i <= upper.get()); It didn't work in our earlier version and it doesn't work with delegation either.

62 Publishing Underlying State Values Is it possible to publish underlying thread-safe state variables? Again, it depends If the possible values or transitions need to be constrained, then probably not If the state is completely self-contained in the threadsafe state variable, then maybe It is probably best to avoid publishing them no matter what, but think long and hard before you do

63 Extending Thread-Safe Classes How do we go about adding functionality to an existing thread-safe class? For example, assume that we want to add a put-ifabsent method on a list collection class The least fragile way is to modify the source code directly Here you will need to understand the class' synchronization policy The benefit is that the synchronization policy is still all contained in a single class Another approach is to create a subclass...

64 Extending Thread-Safe Classes Creating a subclass public class BetterVector<E> extends Vector<E> { public synchronized boolean putifabsent(e x) { boolean absent =!contains(x); if (absent) add(x); return absent;

65 Extending Thread-Safe Classes Creating a subclass public class BetterVector<E> extends Vector<E> { public synchronized boolean putifabsent(e x) { boolean absent =!contains(x); if (absent) add(x); return absent; Still need to understand the synchronization policy...

66 Extending Thread-Safe Classes Creating a subclass public class BetterVector<E> extends Vector<E> { public synchronized boolean putifabsent(e x) { boolean absent =!contains(x); if (absent) add(x); return absent; This is more fragile than modifying the source directly, why?

67 Extending Thread-Safe Classes Creating a subclass public class BetterVector<E> extends Vector<E> { public synchronized boolean putifabsent(e x) { boolean absent =!contains(x); if (absent) add(x); return absent; Synchronization policy is spread across multiple files. If the policy changes, our class will break.

68 Extending Thread-Safe Classes Client-side locking is another approach... public class ListHelper<E> { public List<E> list = Collections.synchronizedList(new ArrayList<E>());... public synchronized boolean putifabsent(e x) { boolean absent =!list.contains(x); if (absent) list.add(x); return absent;

69 Extending Thread-Safe Classes Client-side locking is another approach... public class ListHelper<E> { public List<E> list = Collections.synchronizedList(new ArrayList<E>());... public synchronized boolean putifabsent(e x) { boolean absent =!list.contains(x); if (absent) list.add(x); return absent; Is this good?

70 Extending Thread-Safe Classes Client-side locking is another approach... public class ListHelper<E> { public List<E> list = Collections.synchronizedList(new ArrayList<E>());... public synchronized boolean putifabsent(e x) { boolean absent =!list.contains(x); if (absent) list.add(x); return absent; No, it is not using the correct lock.

71 Extending Thread-Safe Classes Client-side locking is another approach... public class ListHelper<E> { public List<E> list = Collections.synchronizedList(new ArrayList<E>());... public boolean putifabsent(e x) { synchronized (list) { boolean absent =!list.contains(x); if (absent) list.add(x); return absent; Again, we need to understand the synchronization policy.

72 Extending Thread-Safe Classes Composition is another approach... public class ImprovedList<T> implements List<T> { private final List<T> list; public ImprovedList(List<T> list) { this.list = list; public synchronized boolean putifabsent(t x) { boolean contains = list.contains(x); if (contains) list.add(x); return!contains; public synchronized void clear() { list.clear(); //... similarly delegate other List methods

73 Extending Thread-Safe Classes Composition is another approach... public class ImprovedList<T> implements List<T> { private final List<T> list; public ImprovedList(List<T> list) { this.list = list; Is this thread safe? public synchronized boolean putifabsent(t x) { boolean contains = list.contains(x); if (contains) list.add(x); return!contains; public synchronized void clear() { list.clear(); //... similarly delegate other List methods

74 Extending Thread-Safe Classes Composition is another approach... public class ImprovedList<T> implements List<T> { private final List<T> list; public ImprovedList(List<T> list) { this.list = list; Yes. Why is it less fragile? public synchronized boolean putifabsent(t x) { boolean contains = list.contains(x); if (contains) list.add(x); return!contains; public synchronized void clear() { list.clear(); //... similarly delegate other List methods

75 Extending Thread-Safe Classes Composition is another approach... public class ImprovedList<T> implements List<T> { private final List<T> list; public ImprovedList(List<T> list) { this.list = list; Because it defines its own synchronization policy. public synchronized boolean putifabsent(t x) { boolean contains = list.contains(x); if (contains) list.add(x); return!contains; public synchronized void clear() { list.clear(); //... similarly delegate other List methods

76 Extending Thread-Safe Classes Composition is another approach... public class ImprovedList<T> implements List<T> { private final List<T> list; public ImprovedList(List<T> list) { this.list = list; What is the state ownership assumption? public synchronized boolean putifabsent(t x) { boolean contains = list.contains(x); if (contains) list.add(x); return!contains; public synchronized void clear() { list.clear(); //... similarly delegate other List methods

77 Extending Thread-Safe Classes Composition is another approach... public class ImprovedList<T> implements List<T> { private final List<T> list; public ImprovedList(List<T> list) { this.list = list; It owns the passed in list. public synchronized boolean putifabsent(t x) { boolean contains = list.contains(x); if (contains) list.add(x); return!contains; public synchronized void clear() { list.clear(); //... similarly delegate other List methods

78 Documentation As has been shown in these slides, it is very important to document the synchronization policy For maintainers For clients

Composing Objects. Java and Android Concurrency.

Composing Objects. Java and Android Concurrency. Java and Android Concurrency Composing 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

Do inner private classes maintain the thread-safety of the outer class

Do inner private classes maintain the thread-safety of the outer class CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREAD SAFETY] Retrospective on making a thread-safe class better! You may extend, but not always Depends, it does, on the code maze Is the fear of making things

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

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

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

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects CMSC 433 Programming Language Technologies and Paradigms Composing Objects Composing Objects To build systems we often need to Create thread safe objects Compose them in ways that meet requirements while

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

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

Design Patterns. Introduction. Oliver Haase

Design Patterns. Introduction. Oliver Haase Design Patterns Introduction Oliver Haase An instrument, a tool, an utensil, whatsoever it be, if it be fit for the purpose it was made for, it is as it should be though he perchance that made and fitted

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

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

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

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

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

Programming Language Seminar Concurrency 2: Lock-free algorithms

Programming Language Seminar Concurrency 2: Lock-free algorithms Programming Language Seminar Concurrency 2: Lock-free algorithms Peter Sestoft Friday 2013-11-01 1 Outline for today Compare-and-swap instruction Atomic test-then-set operation Implemented directly in

More information

Lecture 7: Process & Thread Introduction

Lecture 7: Process & Thread Introduction COMP 150-CCP Concurrent Programming Lecture 7: Process & Thread Introduction Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 7, 2008 Operating System Concepts Definition of a

More information

CS 520 Theory and Practice of Software Engineering Fall 2017

CS 520 Theory and Practice of Software Engineering Fall 2017 CS 520 Theory and Practice of Software Engineering Fall 2017 Best and worst programming practices September 12, 2017 Logistics Recap: software architecture vs. design Specification Architecture Development

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

CS 520 Theory and Practice of Software Engineering Fall 2018

CS 520 Theory and Practice of Software Engineering Fall 2018 Logistics CS 520 Theory and Practice of Software Engineering Fall 2018 Best and worst programming practices September 11, 2018 Reminder Recap: software architecture vs. design Class website: https://people.cs.umass.edu/~brun/class/2018fall/cs520/

More information

CS 520 Theory and Practice of Software Engineering Fall 2017

CS 520 Theory and Practice of Software Engineering Fall 2017 Logistics CS 520 Theory and Practice of Software Engineering Fall 2017 Best and worst programming practices September 12, 2017 Recap: software architecture vs. design Recap: software architecture examples

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

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

Practical Concurrent and Parallel Programming 10

Practical Concurrent and Parallel Programming 10 Practical Concurrent and Parallel Programming 10 Peter Sestoft IT University of Copenhagen Friday 2016-11-11* IT University of Copenhagen 1 Plan for today Compare and swap (CAS) low-level atomicity Examples:

More information

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency + Lecture 25: Concurrency + Today n Reading n P&C Section 6 n Objectives n Concurrency 1 + Concurrency n Correctly and efficiently controlling access by multiple threads to shared resources n Programming

More information

Section 8: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

Section 8: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst Section 8: Design Patterns Slides by Alex Mariakakis with material from David Mailhot, Hal Perkins, Mike Ernst Announcements HW8 due tonight 10 pm Quiz 7 due tonight 10 pm Industry guest speaker tomorrow!

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

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

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

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

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp CSE 373 Objects in Collections: Object; equals; compareto; mutability slides created by Marty Stepp http://www.cs.washington.edu/373/ University of Washington, all rights reserved. 1 Recall: A typical

More information

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program Lab Lecture 26: Concurrency & Responsiveness CS 62 Fall 2016 Kim Bruce & Peter Mawhorter Using parallelism to speed up sorting using Threads and ForkJoinFramework Review relevant material. Some slides

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

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

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

Topic 10: The Java Collections Framework (and Iterators)

Topic 10: The Java Collections Framework (and Iterators) Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of

More information

Program Graph. Lecture 25: Parallelism & Concurrency. Performance. What does it mean?

Program Graph. Lecture 25: Parallelism & Concurrency. Performance. What does it mean? Program Graph Lecture 25: Parallelism & Concurrency CS 62 Fall 2015 Kim Bruce & Michael Bannister Some slides based on those from Dan Grossman, U. of Washington Program using fork and join can be seen

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

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

COMP 401 INHERITANCE INHERITED VARIABLES AND CONSTRUCTORS. Instructor: Prasun Dewan

COMP 401 INHERITANCE INHERITED VARIABLES AND CONSTRUCTORS. Instructor: Prasun Dewan COMP 401 INHERITANCE INHERITED VARIABLES AND CONSTRUCTORS Instructor: Prasun Dewan PREREQUISITE Inheritance 2 MORE INHERITANCE Inheritance Graphics Examples Inherited Variables Constructors Memory Representation

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

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

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 24 October 29, 2018 Arrays, Java ASM Chapter 21 and 22 Announcements HW6: Java Programming (Pennstagram) Due TOMORROW at 11:59pm Reminder: please complete

More information

Practical Concurrent and Parallel Programming 11

Practical Concurrent and Parallel Programming 11 Practical Concurrent and Parallel Programming 11 Peter Sestoft Friday 2015-11-13* 1 Plan for today Compare and swap (CAS) low-level atomicity Examples: AtomicInteger and NumberRange How to implement a

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 26, 2015 Inheritance and Dynamic Dispatch Chapter 24 public interface Displaceable { public int getx(); public int gety(); public void move

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

Building Java Programs

Building Java Programs Building Java Programs Chapter 8 Lecture 8-3: Encapsulation; Homework 8 (Critters) reading: 8.3-8.4 Encapsulation reading: 8.4 2 Encapsulation encapsulation: Hiding implementation details from clients.

More information

Atomic Variables & Nonblocking Synchronization

Atomic Variables & Nonblocking Synchronization Atomic Variables & Nonblocking Synchronization CMSC 433 Fall 2014 Michael Hicks (with some slides due to Rance Cleaveland) A Locking Counter public final class Counter { private long value = 0; public

More information

Section 9: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

Section 9: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns Slides by Alex Mariakakis with material from David Mailhot, Hal Perkins, Mike Ernst What Is A Design Pattern A standard solution to a common programming problem A technique for

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

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

L13: Synchronization

L13: Synchronization 6.005 Software Construction Fall 2011 Prof. Rob Miller Today o Making a datatype threadsafe o Locks o Monitor pattern o Deadlock o Locking disciplines Required reading (from the Java Tutorial) Synchronization

More information

Applied Unified Ownership. Capabilities for Sharing Across Threads

Applied Unified Ownership. Capabilities for Sharing Across Threads Applied Unified Ownership or Capabilities for Sharing Across Threads Elias Castegren Tobias Wrigstad DRF transfer parallel programming AppliedUnified Ownership memory management placement in pools (previous

More information

CS 360 Programming Languages Introduction to Java

CS 360 Programming Languages Introduction to Java CS 360 Programming Languages Introduction to Java The plan Racket will return! Final project will be writing a Racket interpreter in Java. Lecture will not discuss every single feature of Java. You may

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

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Design for reuse. Design patterns for reuse

Principles of Software Construction: Objects, Design, and Concurrency. Part 1: Design for reuse. Design patterns for reuse Principles of Software Construction: Objects, Design, and Concurrency Part 1: Design for reuse Design patterns for reuse Charlie Garrod Bogdan Vasilescu School of Computer Science 1 Administrivia Homework

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 April 23, 2014 Overriding and Equality HW 10 has a HARD deadline Announcements You must submit by midnight, April 30 th Demo your project to your

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

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

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 25 November 1, 2017 Inheritance and Dynamic Dispatch (Chapter 24) Announcements HW7: Chat Client Available Soon Due: Tuesday, November 14 th at 11:59pm

More information

Objects and Classes (1)

Objects and Classes (1) Objects and Classes (1) Reading: Classes (interface, implementation, garbage collection) http://moodle.cs.man.ac.uk/course/view.php?id=81 Interface Examples Creating and using objects of existing classes

More information

Example: Fibonacci Numbers

Example: Fibonacci Numbers Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter Sharing is the Key Lecture 25: Parallelism CS 62 Fall 2016 Kim Bruce & Peter Mawhorter Some slides based on those from Dan Grossman, U. of Washington Common to have: Different threads access the same resources

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

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

CIS 110: Introduction to Computer Programming

CIS 110: Introduction to Computer Programming CIS 110: Introduction to Computer Programming Lecture 22 and 23 Objects, objects, objects ( 8.1-8.4) 11/28/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Object-oriented programming. What is

More information

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth Outline CIS 110: Introduction to Computer Programming Lecture 22 and 23 Objects, objects, objects ( 8.1-8.4) Object-oriented programming. What is an object? Classes as blueprints for objects. Encapsulation

More information

Quiz 2 (April 22, 2016)

Quiz 2 (April 22, 2016) MIT 6.005: Software Construction Max Goldman revised Friday 22 nd April, 2016, 10:11 Quiz 2 (April 22, 2016) Your name: Your Athena username: You have 50 minutes to complete this quiz. It contains 10 pages

More information

ApacheCon NA How to Avoid Common Mistakes in OFBiz Development Presented by Adrian Crum

ApacheCon NA How to Avoid Common Mistakes in OFBiz Development Presented by Adrian Crum ApacheCon NA 2015 How to Avoid Common Mistakes in OFBiz Development Presented by Adrian Crum 1Tech, Ltd. 29 Harley Street, London, W1G 9QR, UK www.1tech.eu 1 Overview Common Getting Started Problems Common

More information

Section 9: Design Patterns. Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst

Section 9: Design Patterns. Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst Agenda What are design patterns? Creational patterns review Structural patterns

More information

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming) 2014-03-07 Preface Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming) Coordinates: Lecturer: Web: Studies: Requirements: No. 185.211, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/foop.html

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

Final Exam CS 251, Intermediate Programming December 13, 2017

Final Exam CS 251, Intermediate Programming December 13, 2017 Final Exam CS 251, Intermediate Programming December 13, 2017 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

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

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 25 March 18, 2013 Subtyping and Dynamic Dispatch Announcements HW07 due tonight at midnight Weirich OH cancelled today Help your TAs make the most

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int

More information

Java Classes & Primitive Types

Java Classes & Primitive Types Java Classes & Primitive Types Rui Moreira Classes Ponto (from figgeom) x : int = 0 y : int = 0 n Attributes q Characteristics/properties of classes q Primitive types (e.g., char, byte, int, float, etc.)

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

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources Thread-Local Lecture 27: Concurrency 3 CS 62 Fall 2016 Kim Bruce & Peter Mawhorter Some slides based on those from Dan Grossman, U. of Washington Whenever possible, don t share resources Easier to have

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY

EINDHOVEN UNIVERSITY OF TECHNOLOGY EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics & Computer Science Exam Programming Methods, 2IP15, Wednesday 17 April 2013, 09:00 12:00 TU/e THIS IS THE EXAMINER S COPY WITH (POSSIBLY INCOMPLETE)

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

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

Package. A package is a set of related classes Syntax to put a class into a package: Two rules: Example:

Package. A package is a set of related classes Syntax to put a class into a package: Two rules: Example: Packages Package A package is a set of related classes Syntax to put a class into a package: package ; public class { } Two rules: q q A package declaration must always come

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

Midterm Exam CS 251, Intermediate Programming October 8, 2014

Midterm Exam CS 251, Intermediate Programming October 8, 2014 Midterm Exam CS 251, Intermediate Programming October 8, 2014 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Assertions. Assertions - Example

Assertions. Assertions - Example References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 11/13/2003 1 Assertions Statements about input to a routine or state of a class Have two primary roles As documentation,

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

05. SINGLETON PATTERN. One of a Kind Objects

05. SINGLETON PATTERN. One of a Kind Objects BIM492 DESIGN PATTERNS 05. SINGLETON PATTERN One of a Kind Objects Developer: What use is that? Guru: There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle

More information

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Implementing Object Equivalence in Java Using the Template Method Design Pattern Implementing Object Equivalence in Java Using the Template Method Design Pattern Daniel E. Stevenson and Andrew T. Phillips Computer Science Department University of Wisconsin-Eau Claire Eau Claire, WI

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 March 28, 2018 Java Generics Collections and Equality Chapters 25 & 26 Announcements HW7: Chat Server Available on Codio / Instructions on the web

More information