Design Patterns & Concurrency. Sebastian Graf, Oliver Haase

Size: px
Start display at page:

Download "Design Patterns & Concurrency. Sebastian Graf, Oliver Haase"

Transcription

1 Design Patterns & Concurrency Sebastian Graf, Oliver Haase 1

2 Fundamentals 2

3 Recap Threadsafety What is threadsafety? How can threadsafety be ensured? Amdahls Law 3

4 Recap Threadsafety public final class HitCounter { /** internal state counter variable */ private int counter = 0; /** * Getting the counter right now the counts */ public final int getcounter() { return this.counter; /** * Counting multiple values countstoadd numbers to add to the counter */ public final void increment(final int countstoadd) { counter = counter + countstoadd; /** Counting by one */ public final void incrementbyone() { increment(1); 4

5 Recap Threadsafety public final class SynchronizedCounter { /** internal state counter variable */ private int counter = 0; /** * Getting the counter right now the counts */ public synchronized final int getcounter() { return this.counter; /** * Counting multiple values countstoadd numbers to add to the counter */ public synchronized final void increment(final int countstoadd) { counter = counter + countstoadd; /** Counting by one */ public final void incrementbyone() { increment(1); 5

6 Recap Threadsafety import java.util.list; public final class ListSum { /** * Summing multiple variables * multiple * variables the sum of the variables */ public final int sum(final List<Integer> factors) { int sum = 0; for (final int number : factors) { sum = sum + number; return sum; 6

7 Recap Threadsafety public final class IDHandler { /**Local set of ids*/ private String[] ids = { "e634g", "6fhg4", "hd4fg", "dgf53" ; /**Getting the ids. * the ids */ public String[] getids() { return ids; 7

8 Recap Threadsafety public final class IDHandler { /**Local set of ids*/ private final List<String >ids = new ArrayList()<String>; public IDHandler() { ids.add("e634g"); ids.add("6fhg4"); ids.add("hd4fg"); ids.add("dgf53"); /**Getting the ids. * the ids */ public String[] getids() { return ids.toarray(new String[4]); 8

9 Threadsafe? public class ReadyStater { private static boolean ready; private static int number; 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

10 Locking & Visibility 10

11 Difference regarding public class MutableInteger { private int value; public int get() { return value; public void set(int value) { this.value = public class MutableInteger { private long value; public long get() { return value; public void set(long value) { this.value = value; 11

12 Always Synchronize? public class MutableInteger { private long value; public synchronized long get() { return value; public synchronized void set(long value) { this.value = value; public class MutableInteger { private volatile long value; public long get() { return value; public void set(long value) { this.value = value; 12

13 Volatile VS Synchronize No Locking Volatile no synchronization visibility Usage: using if only one thread updates value OR value is not participating to invariants OR any other reason Locking Synchonize synchronization visibility Usage: guarding multiple variables (invariants) accessing within multiple threads 13

14 Publishing and Escaping Publishing: Making a variable visible out of its current scope Escaping: Doing the same by accident public final class IDHandler { /**Local set of ids*/ private String[] ids = { "e634g", "6fhg4", "hd4fg", "dgf53" ; /**Getting the ids. * the ids */ public String[] getids() { return ids; 14

15 Escaping in Construtor public class ThisEscape { public ThisEscape(EventSource source) { source.registerlistener( new EventListener() { public void onevent(event e) { dosomething(e); ); 15

16 Safe Construction Process Do not allow to escape this during construction. public class SafeListener { private final EventListener listener; private SafeListener() { listener = new EventListener() { public void onevent(event e) { dosomething(e); ; public static SafeListener newinstance(eventsource source) { SafeListener safe = new SafeListener(); source.registerlistener(safe.listener); return safe; 16

17 Further techniques to ensure thread safety Confinement Immutability Publication Design Documentation 17

18 Confinement Thread Confinement Binding an object to exactly one thread (which cannot be enforced by the JVM) Ad-hoc Confinement Responsibility of maintaining thread safety is on implementation side (which is mostly fragile) Stack Confinement Object bound to local variables only (happening in methods) ThreadLocal private static ThreadLocal<Connection> connectionholder = new ThreadLocal<Connection>() { public Connection initialvalue() { return DriverManager.getConnection(DB_URL); ; public static Connection getconnection() { return connectionholder.get(); 18

19 Immutability Criterias for Immutability State cannot be modified after construction All fields are final properly constructed Immutable Objects are always thread-safe! 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); 19

20 Immutability and 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, public class VolatileCachedFactorizer 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); 20

21 Publishing of data public Holder holder; public void initialize() { holder = new Holder(42); 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."); 21

22 Safe publication idioms Initialize objects references from a static initializer Storing a reference into a volatile or AtomicReference Storing a reference into a final field of a proper constructed object Guard the field that stores the object with a lock Publication requirements Immutable objects: can be published with any mechanism Effectively immutable objects: must be published safely Mutable objects: must be published safely and be guared by a lock 22

23 Useful policies for sharing objects Thread-confined: Object is owned exclusively by one thread Shared read-only: Object can be accessed concurrently by multiple threads without additional synchronization Shared thread-safe: Synchronization on object is handled internally. Guarded: Access to the object only possible when given lock held including encluding other thread-safe objects 23

24 Designing Objects Identify the variables that form the object's state; Identify the invariants that constrain the state variables; Establish a policy for managing concurrent access to the object's state 24

25 States? State of an object includes state of all fields primitive: simple n-primitives: n-tuple of the fields LinkedList: all linked nodes Stay aware of pre-/postconditions and invariants: Synchronization-Policy 25

26 Thread-Safety redefined Making a class thread-safe means ensuring that its invariants hold under concurrent access; this requires reasoning about its public final class Counter private long value = 0; public synchronized long getvalue() { return value; public synchronized long increment() { if (value == Long.MAX_VALUE) throw new IllegalStateException("counter overflow"); return ++value; 26

27 Instance Confinement Useful for debugging issues Guarding the access with wrapper Class itself is thread-safe (as are the states only accessible within this class) Example: Collections.synchronizedList representing Decorator-Pattern for guarding collections Caution: wrapped object must not escape! 27

28 Monitor-Based Locking Each object holds its own public final class Counter private long value = 0; public synchronized long getvalue() { return value; public synchronized long increment() { if (value == Long.MAX_VALUE) throw new IllegalStateException("counter overflow"); return ++value; 28

29 Public VS Private Locking public class PrivateLock { private final Object mylock = new Widget widget; void somemethod() { synchronized(mylock) { // Access or modify the state of widget public class PublicLock Widget widget; void synchronized somemethod() { // Access or modify the state of widget 29

30 Delegation of Thread safety 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; 30

31 Delegation of Thread 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); 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); 31

32 public class Point { public final int x, y; public Point(int x, int y) { this.x = x; this.y = y; 32

33 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 vehicle name: " + id); 33

34 Independence of state variables 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); 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()); 34

35 Extending existing sources Extending? Inheritence? Composition? Locking is based on functionality to be offered Alien-Calls in foreign source code complicate things further. 35

36 What to lock? 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; 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; 36

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

38 Further Example: BlockingQueues BlockingQueue Pill Item Item Item Item Item Item Item Item Producer Consumer Void call() Void call() 38

39 Documentation Each use of volatile / synchronize reflects a synchronization strategy for mainting invariants/pre-/post-conditions JavaDoc (often not really usable regarding thread safety) Assumptions Annotations 39

40 @NotThreadSafe Field- this (Class.)fieldName methodname() ) 40

41 Outcome of first part It's the mutable state, stupid. Make fields final unless they need to be mutable. Immutable objects are automatically thread-safe. Encapsulation makes it practical to manage the complexity. Guard each mutable variable with a lock. Guard all variables in an invariant with the same lock. Hold locks for the duration of compound actions. A program that accesses a mutable variable from multiple threads without synchronization is a broken program. Don't rely on clever reasoning about why you don't need to synchronize. Include thread safety in the design processor explicitly document that your class is not threadsafe. Document your synchronization policy. 41

42 Structuring Applications 42

43 Task Execution class ThreadPerTaskWebServer { public static void main(string[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { final Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handlerequest(connection); ; new Thread(task).start(); 43

44 How to start a thread Thread 0 void sum(final int[][] numbers) Starting of threads should be based on defined pool of threads Runnable 1 Runnable 2 run() run() Support of lifecycle as well Runnable 3 Runnable 4 run() run() Runnable 5 Runnable 6 run() run() 44

45 A summing example public void sum(final int[][] numbers) { final List<Future<Integer>> futures = new ArrayList<Future<Integer>>(); final ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < numbers.length; i++) { final int index = i; Callable<Integer> summer = new Callable<Integer>() { public Integer call() throws Exception { return sum; ; futures.add(exec.submit(summer)); // getting all futures for (int i = 0; i < futures.size(); i++) { try { returnval[i] = futures.get(i).get(); catch (final InterruptedException e) { e.printstacktrace(); returnval[i] = Integer.MIN_VALUE; catch (final ExecutionException e) { e.printstacktrace(); returnval[i] = Integer.MIN_VALUE; Thread 0 int[] sum(final int[][] numbers) ExecutorService.submit Callable 1 Callable 2 Integer call() Integer call() FutureList.add FutureList.get Future.get 45

46 Advantages of bound execution Defined Thread lifecycle Adaptive and independent resource management Stability 46

47 Hazards while not using Executors Thread 0 void sum(final int[][] numbers) Runnable 1 Runnable 2 run() run() Runnable 3 Runnable 4 run() run() Runnable 5 Runnable 6 run() run() 47

48 Further Hazards Poor Exception-Handling Overwhelming the resources Hard support for individual multithreaded tasks Unequal tasks Scheduling Cancelation No lifecycle for execution itself 48

49 Executors Fixed Pool Size Queue ExecutorService ThreadFactory Thread Thread Thread Thread Thread Pool Size = 1 Queue ExecutorService ThreadFactory Thread Additional Executors: ScheduledExecutor, CompletionServiceExecutor No Pool Size Queue ExecutorService ThreadFactory Thread Thread Thread Thread Thread Thread Thread Thread Thread 49

50 Stopping Threads... 50

51 There is no safe way to stop a thread public class PrimeGenerator implements Runnable private final List<BigInteger> primes = new ArrayList<BigInteger>(); private volatile boolean cancelled; public void run() { BigInteger p = BigInteger.ONE; while (!cancelled ) { p = p.nextprobableprime(); synchronized (this) { primes.add(p); public void cancel() { Thread.stop(); public synchronized List<BigInteger> get() { return new ArrayList<BigInteger>(primes); 51

52 public class PrimeGenerator implements Runnable private final List<BigInteger> primes = new ArrayList<BigInteger>(); private volatile boolean cancelled; public void run() { BigInteger p = BigInteger.ONE; while (!cancelled ) { p = p.nextprobableprime(); synchronized (this) { primes.add(p); public void cancel() { cancelled = true; public synchronized List<BigInteger> get() { return new ArrayList<BigInteger>(primes); 52

53 Producer / Consumer? class BrokenPrimeProducer extends Thread { private final BlockingQueue<BigInteger> queue; private volatile boolean cancelled = false; BrokenPrimeProducer(BlockingQueue<BigInteger> queue) { this.queue = queue; public void run() { try { BigInteger p = BigInteger.ONE; while (!cancelled) queue.put(p = p.nextprobableprime()); catch (InterruptedException consumed) { public void cancel() { cancelled = true; void consumeprimes() throws InterruptedException { BlockingQueue<BigInteger> primes =...; BrokenPrimeProducer producer = new BrokenPrimeProducer(primes); producer.start(); try { while (needmoreprimes()) consume(primes.take()); finally { producer.cancel(); 53

54 Interruption? class PrimeProducer extends Thread { private final BlockingQueue<BigInteger> queue; PrimeProducer(BlockingQueue<BigInteger> queue) { this.queue = queue; public void run() { try { BigInteger p = BigInteger.ONE; while (!Thread.currentThread().isInterrupted()) queue.put(p = p.nextprobableprime()); catch (InterruptedException consumed) { /* Allow thread to exit */ public void cancel() { interrupt(); 54

55 Interruption Necessary Interruption Policy (what should happen if thread gets interrupted) freeing connection, resources unblocking keeping invariants cleaning up Tasks own not the thread (with the usage of thread pools), policy mostly based on get out of the way 55

56 Interruption What to do if InterruptedException is catched? Propagate the Interruption Restore the internal state public Task getnexttask(blockingqueue<taskgt; queue) { boolean interrupted = false; try { while (true) { try { return queue.take(); catch (InterruptedException e) { interrupted = true; // fall through and retry finally { if (interrupted) Thread.currentThread().interrupt(); 56

57 Interruption of other threads private static final ScheduledExecutorService cancelexec =...; public static void timedrun(runnable r, long timeout, TimeUnit unit) { final Thread taskthread = Thread.currentThread(); cancelexec.schedule(new Runnable() { public void run() { taskthread.interrupt();, timeout, unit); r.run(); 57

58 Future.cancel public static void timedrun(runnable r, long timeout, TimeUnit unit) throws InterruptedException { Future<?> task = taskexec.submit(r); try { task.get(timeout, unit); catch (TimeoutException e) { // task will be cancelled below catch (ExecutionException e) { // exception thrown in task; rethrow throw launderthrowable(e.getcause()); finally { // Harmless if task already completed task.cancel(true); // interrupt if running 58

59 Producer / Consumer, Poison Pill BlockingQueue Pill Item Item Item Item Item Item Item Item Producer Consumer Void call() Void call() 59

60 Executor Shutdown? public class LogService { private final ExecutorService exec = newsinglethreadexecutor();... public void start() { public void stop() throws InterruptedException { try { exec.shutdown(); exec.awaittermination(timeout, UNIT); finally { writer.close(); public void log(string msg) { try { exec.execute(new WriteTask(msg)); catch (RejectedExecutionException ignored) { 60

61 Exceptions? public void log(string msg) throws InterruptedException { if (!shutdownrequested) queue.put(msg); else throw new IllegalStateException("logger is shut down"); 61

62 Always be aware of the exceptions Proactive reaction regarding exceptions Propagate the Interruption Restore the internal state UncaughtExceptionHandler for detection of uncaught exceptions 62

63 Other artifacts Finalizers Daemon Threads JVM Shutdowns 63

64 The last one public interface Runnable2 { public void run() throws Exception; 64

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

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

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

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

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

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

[module lab 1.3] CANCELLATION AND SHUTDOWN

[module lab 1.3] CANCELLATION AND SHUTDOWN v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.3] CANCELLATION AND SHUTDOWN 1 STOPPING THREADS AND TASKS An activity is cancellable if external

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

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

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci v1.0 20130510 Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci [module lab 3.1] TASK FRAMEWORKS 1 STRUCTURING CONCURRENT PROGRAMS INTO

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

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

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

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

[module lab 1.2] STRUCTURING PROGRAMS IN TASKS

[module lab 1.2] STRUCTURING PROGRAMS IN TASKS v1.0 Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.2] STRUCTURING PROGRAMS IN TASKS 1 STRUCTURING CONCURRENT PROGRAMS INTO TASKS Task concept abstract,

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

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

Concurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Concurrency in Object Oriented Programs 4 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism

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

Concurrency Utilities: JSR-166

Concurrency Utilities: JSR-166 Concurrency Concurrency Utilities: JSR-166 Enables development of simple yet powerful multi-threaded applications > Like Collection provides rich data structure handling capability Beat C performance in

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

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

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

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

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

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

Northeastern University - Seattle CS5510 Professor Ian Gorton

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

More information

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

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

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

Final Concurrency. Oleg October 27, 2014

Final Concurrency. Oleg October 27, 2014 Final Concurrency Oleg Šelajev @shelajev oleg@zeroturnaround.com October 27, 2014 Feedbacks Task Executors Fork-Join framework Completable Future Agenda 2 HOMEWORK 4 FEEDBACK THREAD LOCAL VARIABLES TASK

More information

CONCURRENT API AND PARALLEL PROGRAMMING

CONCURRENT API AND PARALLEL PROGRAMMING MODULE 11 CONCURRENT API AND PARALLEL PROGRAMMING Module 11.A THREAD MODEL: RUNNABLE, CALLABLE, FUTURE, FUTURETASK Threads > What are threads? Threads are a virtual CPU. > The three parts of at thread

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

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

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

Index. Symbols 64-bit operations nonatomic nature of; 36

Index. Symbols 64-bit operations nonatomic nature of; 36 Index Symbols 64-bit operations nonatomic nature of; 36 A ABA problem; 336 abnormal thread termination handling; 161 163 abort saturation policy; 174 See also lifecycle; termination; abrupt shutdown limitations;

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

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

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

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

More information

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

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

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

More information

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

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

More information

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

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

More information

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

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

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

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

SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS

SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS SUMMARY CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS Callable tasks Futures Executors Executor services Deadlocks PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento

More information

Chapter 8 Applying Thread Pools. Magnus Andersson

Chapter 8 Applying Thread Pools. Magnus Andersson Chapter 8 Applying Thread Pools Magnus Andersson Execution policies Not all task are suitable for all execution policies Dependent task Task exploiting thread confinement Response time sensitive tasks

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

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

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

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

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

Programming in Java

Programming in Java 320341 Programming in Java Fall Semester 2014 Lecture 11: Introduction to Concurrency Instructor: Slides: Jürgen Schönwälder Bendick Mahleko Introduction Multithreaded Programs - A program represents separate,

More information

Thread Pools SE 441. Prof. Bullinger

Thread Pools SE 441. Prof. Bullinger Thread Pools SE 441 Prof. Bullinger Thread Pools Thread Pool Limitations Sizing Thread Pools ThreadPoolExecutor Queuing Tasks Parallelizing Loops Thread Pool Limitations Task Dependencies Different types

More information

Basics of. Multithreading in Java

Basics of. Multithreading in Java Basics of programming 3 Multithreading in Java Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction

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

Concurrent and Real-Time Programming in Java

Concurrent and Real-Time Programming in Java 064202 Degree Examinations 2003 DEPARTMENT OF COMPUTER SCIENCE Concurrent and Real-Time Programming in Java Time allowed: One and one half (1.5) hours Candidates should answer not more than two questions.

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

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

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

More information

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

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

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

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar JAVA CONCURRENCY FRAMEWORK Kaushik Kanetkar Old days One CPU, executing one single program at a time No overlap of work/processes Lots of slack time CPU not completely utilized What is Concurrency Concurrency

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

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

Advanced Concepts of Programming

Advanced Concepts of Programming Berne University of Applied Sciences E. Benoist / E. Dubuis January 2005 1 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate

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

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

-Aditya Bhave CSCI-5448 Graduate Presentation

-Aditya Bhave CSCI-5448 Graduate Presentation -Aditya Bhave CSCI-5448 Graduate Presentation 04-01-2011 MSEE at CU finishing up in Summer 11 Work full time at Alticast Inc Background in Embedded Systems Media Processing Middleware Cable TV industry

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

Multi-threaded Performance And Scalability

Multi-threaded Performance And Scalability 1 Multi-threaded Performance And Scalability Dr Heinz M. Kabutz 2012 Heinz Kabutz All Rights Reserved Multi-threaded Performance and Scalability Dr Heinz Kabutz Brief Biography Lives in Chania on the Island

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

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

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

Intro to multi-threaded programming in Java

Intro to multi-threaded programming in Java jonas.kvarnstrom@liu.se 2015 Intro to multi-threaded programming in Java Intro 1: Multitasking Most operating systems allow multitasking Multiple tasks are run in parallel (given enough processor cores)

More information

Part IV Other Systems: I Java Threads

Part IV Other Systems: I Java Threads Part IV Other Systems: I Java Threads Spring 2019 C is quirky, flawed, and an enormous success. 1 Dennis M. Ritchie Java Threads: 1/6 Java has two ways to create threads: Create a new class derived from

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

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

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

Multithreading and Interactive Programs

Multithreading and Interactive Programs Multithreading and Interactive Programs CS160: User Interfaces John Canny. This time Multithreading for interactivity need and risks Some design patterns for multithreaded programs Debugging multithreaded

More information

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Concurrency.   CSCI 136: Fundamentals of Computer Science II Keith Vertanen Concurrency http://csunplugged.org/routing-and-deadlock CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Multi-threaded programs Multiple simultaneous paths of execution Seemingly

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

Threads Chate Patanothai

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

More information

Charlie Garrod Bogdan Vasilescu

Charlie Garrod Bogdan Vasilescu Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 4: Concurrency Introduc9on to concurrency, part 4 Design paderns and frameworks for concurrency Charlie Garrod Bogdan Vasilescu

More information

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization COMP 213 Advanced Object-oriented Programming Lecture 23 Shared Variables and Synchronization Communicating Threads In the previous lecture, we saw an example of a multi-threaded program where three threads

More information

Concurrency. Fundamentals of Computer Science

Concurrency.  Fundamentals of Computer Science Concurrency http://csunplugged.org/routing-and-deadlock Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually

More information

Java Memory Model for practitioners. by Vadym Kazulkin and Rodion Alukhanov, ip.labs GmbH

Java Memory Model for practitioners. by Vadym Kazulkin and Rodion Alukhanov, ip.labs GmbH Java Memory Model for practitioners by Vadym Kazulkin and Rodion Alukhanov, ip.labs GmbH Topics Hardware Memory Model Java Memory Model Practical examples related to Java Memory Model JcStress Tool The

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

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

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

WINDOWS SOCKET PROGRAMMING

WINDOWS SOCKET PROGRAMMING WINDOWS SOCKET PROGRAMMING Headers and libraries All the declarations are in one header, winsock.h Your socket programs must link to the Winsock library (usually called wsock32.lib or winsock32.lib) Initialization

More information

UNIT V CONCURRENT PROGRAMMING

UNIT V CONCURRENT PROGRAMMING UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such

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

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

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

public static boolean isoutside(int min, int max, int value)

public static boolean isoutside(int min, int max, int value) See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static

More information

Multithreaded Programming

Multithreaded Programming core programming Multithreaded Programming 1 2001-2003 Marty Hall, Larry Brown http:// 2 Multithreaded Programming Agenda Why threads? Approaches for starting threads Separate class approach Callback approach

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information