CONCURRENT API AND PARALLEL PROGRAMMING

Size: px
Start display at page:

Download "CONCURRENT API AND PARALLEL PROGRAMMING"

Transcription

1 MODULE 11 CONCURRENT API AND PARALLEL PROGRAMMING Module 11.A THREAD MODEL: RUNNABLE, CALLABLE, FUTURE, FUTURETASK

2 Threads > What are threads? Threads are a virtual CPU. > The three parts of at thread are: CPU Code Data Creating the Thread

3 Creating the Thread > Multithreaded programming has these characteristics: Multiple threads are from one Runnable instance. Threads share the same data and code. > For example: Thread t1 = new Thread(r); Thread t2 = new Thread(r); > Use the start method. Starting the Thread > Place the thread in a runnable state.

4 Thread Scheduling Daemon Threads > You can turn a thread into a daemon thread by calling t.setdaemon(true); > This method must be called before the thread is started. > A daemon is simply a thread that has no other role in life than to serve others. > When only daemon threads remain, the virtual machine exits. > A daemon thread should never access a persistent resource such as a file or database since it can terminate at any time, even in the middle of an operation.

5 Thread Scheduling Example Terminating a Thread

6 Terminating a Thread > A thread terminates when its run method returns, by executing a return statement, after executing the last statement in the method body, or if an exception occurs that is not caught in the method. > In the initial release of Java, there also was a stop method that another thread could call to terminate a thread. > However, that method is now deprecated. Terminating a Thread > There is a way to force a thread to terminate. > However, the interrupt method can be used to request termination of a thread. > When the interrupt method is called on a thread, the interrupted status of the thread is set. > This is a boolean flag that is present in every thread. > Each thread should occasionally check whether it has been interrupted. while (!Thread.currentThread().isInterrupted()) { } do more work

7 Terminating a Thread > There is no language requirement that a thread that is interrupted should terminate. > Interrupting a thread simply grabs its attention. The interrupted thread can decide how to react to the interruption. > Some threads are so important that they should handle the exception and continue. > But quite commonly, a thread will simply want to interpret an interruption as a request for termination. > Test threads: isalive() > Access thread priority: getpriority() setpriority() Basic Control of Threads > Put threads on hold: Thread.sleep() // static method join() Thread.yield() // static method

8 The join Method Handlers for Uncaught Exceptions > The run method cannot throw any checked exceptions, but it can be terminated by an unchecked exception. In that case, the thread dies. > However, there is no catch clause to which the exception can be propagated. Instead, just before the thread dies, the exception is passed to a handler for uncaught exceptions. > You can install a handler into any thread with the setuncaughtexceptionhandler method. > You can also install a default handler for all threads with the static method setdefaultuncaughtexceptionhandler of the Thread class.

9 java.lang.thread > static void setdefaultuncaughtexceptionhandler( Thread.UncaughtExceptionHandler handler) > static Thread.UncaughtExceptionHandler getdefaultuncaughtexceptionhandler() sets or gets the default handler for uncaught exceptions. > void setuncaughtexceptionhandler( Thread.UncaughtExceptionHandler handler) > Thread.UncaughtExceptionHandler getuncaughtexceptionhandler() sets or gets the handler for uncaught exceptions. If no handler is installed, the thread group object is the handler. java.lang.thread.uncaughtexceptionhandler >void uncaughtexception(thread t, Throwable e) defined to log a custom report when a thread is terminated with an uncaught exception. > Parameters t The thread that was terminated due to an uncaught exception e The uncaught exception object

10 Thread t= new Thread(new Runnable() public void run() { } }); throw new IllegalArgumentException(); t.setuncaughtexceptionhandler( new Thread.UncaughtExceptionHandler() }); public void uncaughtexception(thread t, } Throwable e) { System.err.println(e.getMessage()); t.start(); Callables and Futures > A Runnable encapsulates a task that runs asynchronously; you can think of it as an asynchronous method with no parameters and no return value. > A Callable is similar to a Runnable, but it returns a value. > The Callable interface is a parameterized type, with a single method call. public interface Callable<V> { } V call() throws Exception;

11 Callables and Futures > A Future holds the result of an asynchronous computation. > Use a Future object so that you can start a computation, give the result to someone, and forget about it. > The owner of the Future object can obtain the result when it is ready: public interface Future<V> { V get() throws...; V get(long timeout, TimeUnit unit); void cancel(boolean mayinterrupt); boolean iscancelled(); boolean isdone(); } get() > A call to the first get method blocks until the computation is finished. > The second method throws a TimeoutException if the call timed out before the computation finished. > If the thread running the computation is interrupted, both methods throw an InterruptedException. > If the computation has already finished, then get returns immediately.

12 isdone() > The isdone method returns false if the computation is still in progress, true if it is finished. iscancelled() > You can cancel the computation with the cancel method. > If the computation has not yet started, it is canceled and will never start. > If the computation is currently in progress, then it is interrupted if the mayinterrupt parameter is true.

13 FutureTask > The FutureTask wrapper is a convenient mechanism for turning a Callable into both a Future and a Runnable, it implements both interfaces: Callable<Integer> mycomputation =...; FutureTask<Integer> task = new FutureTask<Integer>(myComputation); Thread t = new Thread(task); t.start();... Integer result = task.get(); Module 11.B THREAD SYNCHRONIZATION

14 Using the synchronizedkeyword The Object Lock Flag > Every object has a flag that is a type of lock flag. > The synchronized enables interaction with the lock flag.

15 The Object Lock Flag The Object Lock Flag

16 Releasing the Lock Flag >The lock flag is released in the following events: > Released when the thread passes the end of the synchronized code block > Released automatically when a break, return, or exception is thrown by the synchronized code block Synchronization

17 Thread Interaction wait and notify > Scenario: Consider yourself and a cab driver as two threads. > The problem: How do you determine when you are at your destination? > The solution: You notify the cab driver of your destination and relax. The driver drives and notifies you upon arrival at your destination. Thread Interaction >Thread interactions include: > The wait and notify methods > The pools: Wait pool Lock pool

18 Thread State Diagram With wait and notify Monitor Model for Synchronization > Leave shared data in a consistent state. > Ensure programs cannot deadlock. > Do not put threads expecting different notifications in the same wait pool.

19 The Producer Class The Producer Class

20 The Consumer Class The Consumer Class

21 The SyncStack Class This is a sketch of the SyncStack class: The pop Method

22 The push Method The SyncTest Class

23 Concurrency Library > The concurrency library has convenient, high-level utilities for developing high-performence, multi-threaded programs. > The concurrency library frees you from having to develop those utilities by hand (based upon low-level language concurrency primitives) Advantages > Reduced programming effort: It is easier to use a standard class than re-inventing the wheel > Increased performance: The implementations have been developed and tested by concurrency and performance experts, and therefore, they are faster and more scalable than typical implementations > Increased reliability: The low-level concurrency primitives (such as synchronized, wait(), and notify()) are difficult to use correctly and errors are not easy to detect or debug. On the other hand, the concurrency utilities are standardized and extensively tested against deadlock, starvation, or race conditions.

24 Advantages > Improved maintainability: Applications that are based on standardized packages are easier to maintain > Increased productivity: Programmers are likely to already understand the standard library classes, so there is no need to learn new APIs Libraries > java.util.concurrent Classes commonly used in concurrent programming, for example, thread pools > java.util.concurrent.atomic Classes that support atomic operations on single variables, for example, atomic counters > java.util.concurrent.locks Classes for locking and waiting for conditions

25 Lock Objects > Starting with Java SE 5.0, there are two mechanisms for protecting a code block from concurrent access. 1. The Java language provides a synchronized keyword for this purpose 2. Java SE 5.0 introduced the ReentrantLock class. mylock.lock(); // a ReentrantLock object try { critical section } finally { mylock.unlock(); } java.util.concurrent.locks.lock > void lock() acquires this lock; blocks if the lock is currently owned by another thread. > void unlock() releases this lock.

26 java.util.concurrent.locks.reentrantlock > ReentrantLock() constructs a reentrant lock that can be used to protect a critical section. > ReentrantLock(boolean fair) constructs a lock with the given fairness policy. A fair lock favors the thread that has been waiting for the longest time. However, this fairness guarantee can be a significant drag on performance. Therefore, by default, locks are not required to be fair. ReentrantReadWriteLock > ReentrantReadWriteLock Provides better performance in cases where there are many readers but few writers. readlock() writelock() getreadholdcount() getwriteholdcount()

27 Condition Objects > A thread enters a critical section, only to discover that it can t proceed until a condition is fulfilled. Condition condition= lock.newcondition(); > You use a condition object to manage threads that have acquired a lock but cannot do useful work. while (!(ok to proceed)) condition.await(); > Some other thread calls signalall eventually > Note that the call to signalall does not immediately activate a waiting thread. It only unblocks the waiting threads so that they can compete for entry into the object after the current thread has exited the synchronized method. Module 11.C EXECUTORS

28 Executors > Constructing a new thread is somewhat expensive because it involves interaction with the operating system. > If your program creates a large number of short-lived threads, then it should instead use a thread pool. > A thread pool contains a number of idle threads that are ready to run. > You give a Runnable to the pool, and one of the threads calls the run method. > When the run method exits, the thread doesn't die but stays around to serve the next request. Executors > The Executors class has a number of static factory methods for constructing thread pools Method newcachedthreadpool newfixedthreadpool newsinglethreadexecutor newscheduledthreadpool newsinglethreadscheduledexecutor Description New threads are created as needed; idle threads are kept for 60 seconds. The pool contains a fixed set of threads; idle threads are kept indefinitely. A "pool" with a single thread that executes the submitted tasks sequentially. A fixed-thread pool for scheduled execution. A single-thread "pool" for scheduled execution.

29 Thread Pools > You can submit a Runnable or Callable to an ExecutorService with one of the following methods: Future<?> submit(runnable task) Future<T> submit(runnable task, T result) Future<T> submit(callable<t> task) > The pool will run the submitted task at its earliest convenience. > When you call submit, you get back a Future object that you can use to query the state of the task. Thread Pools 1. Call the static newcachedthreadpool or newfixedthreadpool method of the Executors class. 2. Call submit to submit Runnable or Callable objects. 3. If you want to be able to cancel a task or if you submit Callable objects, hang on to the returned Future objects. 4. Call shutdown when you no longer want to submit any tasks.

30 Module 11.D SYNCHRONIZERS java.util.concurrent.atomic > The classes in this package allow multiple operations to be treated atomically. > As an example, a volatile integer cannot be used with the ++ operator because this operator contains multiple instructions. > The AtomicInteger class has a method that allows the integer it holds to be incremented atomically without using synchronization. > Atomic classes, however, can be used for more complex tasks, such as building code that requires no synchronization

31 Example import java.util.concurrent.atomic.*; public class SequenceGenerator { private AtomicLong number = new AtomicLong(0); public long next() { return number.getandincrement(); } } java.util.concurrent.atomic > Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type. > Atomic classes don t inherit from the similarly named classes, so AtomicBoolean can t be used in place of a Boolean, and AtomicInteger isn t an Integer

32 Synchronizers > The java.util.concurrent package contains several classes that help manage a set of collaborating threads > These mechanisms have "canned functionality" for common rendezvous patterns between threads. > If you have a set of collaborating threads that follows one of these behavior patterns, you should simply reuse the appropriate library class instead of trying to come up with a handcrafted collection of locks. Synchronizers Class What It Does When To Use CyclicBarrier CountDownLatch Exchanger Allows a set of threads to wait until a predefined count of them has reached a common barrier, and then optionally executes a barrier action. Allows a set of threads to wait until a count has been decremented to 0. Allows two threads to exchange objects when both are ready for the exchange. When a number of threads need to complete before their results can be used. When one or more threads need to wait until a specified number of results are available. When two threads work on two instances of the same data structure, one by filling an instance and the other by emptying the other.

33 Synchronizers Class What It Does When To Use SynchronousQueue Allows a thread to hand off an object to another thread. To send an object from one thread to another when both are ready, without explicit synchronization. Semaphore Allows a set of threads to wait until permits are available for proceeding. To restrict the total number of threads that can access a resource. If permit count is one, use to block threads until another thread gives permission. Barriers > The CyclicBarrier class implements a rendezvous called a barrier. > Consider a number of threads that are working on parts of a computation. > When all parts are ready, the results need to be combined. > When a thread is done with its part, we let it run against the barrier. > Once all threads have reached the barrier, the barrier gives way and the threads can proceed. > Here are the details.

34 Barriers > First, construct a barrier, giving the number of participating threads: CyclicBarrier barrier = new CyclicBarrier(nthreads); > Each thread does some work and calls await on the barrier upon completion: public void run() { } dowork(); barrier.await();... > The await method takes an optional timeout parameter barrier.await(100, TimeUnit.MILLISECONDS); Countdown Latches > A CountDownLatch lets a set of threads wait until a count has reached zero. > It differs from a barrier in these respects: Not all threads need to wait for the latch until it can be opened. The latch can be counted down by external events. The countdown latch is one-time only. Once the count has reached 0, you cannot reuse it. A useful special case is a latch with a count of 1. This implements a one-time gate. Threads are held at the gate until another thread sets the count to 0.

35 java.util.concurrent.countdownlatch > CountdownLatch(int count) constructs a countdown latch with the given count. > void await() waits for this latch to count down to 0. > boolean await(long time,timeunit unit) waits for this latch to count down to 0 or for the timeout to elapse. Returns true if the count is 0, false if the timeout elapsed. > public void countdown() counts down the counter of this latch. Exchangers > An Exchanger is used when two threads are working on two instances of the same data buffer. > Typically, one thread fills the buffer, and the other consumes its contents. When both are done, they exchange their buffers.

36 java.util.concurrent.exchanger<v> V exchange(v item) V exchange(v item, long time, TimeUnit unit) blocks until another thread calls this method, and then exchanges the item with the other thread and returns the other thread's item. The second method throws a TimeoutException after the timeout has elapsed. Exchanger - Example >Consumer Thread try { while (currentbuffer!= null) { takefrombuffer(currentbuffer); if (currentbuffer.empty()) currentbuffer= exchanger.exchange(currentbuffer); } } catch (InterruptedException ex) { //... handle... }

37 Exchanger - Example >Producer Thread try { while (currentbuffer!= null) { addtobuffer(currentbuffer); if (currentbuffer.full()) currentbuffer=exchanger.exchange(currentbuffer); } } catch (InterruptedException ex) { //... handle... } Semaphores > Conceptually, a semaphore manages a number of permits. > To proceed past the semaphore, a thread requests a permit by calling acquire. > Only a fixed number of permits are available, limiting the number of threads that are allowed to pass. > Other threads may issue permits by calling release. > There are no actual permit objects. > The semaphore simply keeps a count.

38 Semaphores > Moreover, a permit doesn't have to be released by the thread that acquires it. > In fact, any thread can issue any number of permits. > If it issues more than the maximum available, the semaphore is simply set to the maximum count. This generality makes semaphores both very flexible and potentially confusing. > Semaphores were invented by Edsger Dijkstra in 1968, for use as a synchronization primitive. > Dijkstra showed that semaphores can be efficiently implemented and they are powerful enough to solve many common thread synchronization problems. java.util.concurrent.semaphore > Semaphore(int permits) > Semaphore(int permits, boolean fair) construct a semaphore with the given maximum number of permits. If fair is true, the queue favors the longestwaiting threads. > void acquire() > void acquire(int permits) waits to acquire a permit. > boolean tryacquire() tries to acquire a permit; returns false if none is available.

39 java.util.concurrent.semaphore > boolean tryacquire(long time,timeunit unit) tries to acquire a permit within the given time; returns false if none is available. > void release() releases a permit. Quiz #1 > In order to ensure that a service does not start until other services on which it depends have started, which Synchronizer is best suited for this purpose? a) CyclicBarrier b) CountDownLatch c) Exchanger d) Semaphore

40 Quiz #2 > In order to implement database connection pool, which Synchronizer is best suited for this purpose? a) CyclicBarrier b) CountDownLatch c) Exchanger d) Semaphore Quiz #3 > Multiple threads are downloading files, and you want to keep track of the total number of bytes that have been downloaded. Which of the followings is best suited for this purpose? a) Executor b) CyclicBarrier c) AtomicInteger d) Semaphore e) LinkedBlockingQueue

41 Quiz #4 > A thread is computing a value; other threads may need/request that value and if they need/request it before it is computed those threads should block until the value is ready. Which of the followings is best suited for this purpose? a) Lock b) Future c) AtomicInteger d) Semaphore e) AtomicBoolean Quiz #5 > You are going to create 8 threads for testing purposes, and you don t want the first thread that is started to begin executing some test code before the other threads have been started. Instead, you want to ensure that all threads have been started and that control has entered their run methods before any of them execute the test code. Which Synchronizer is best suited for this purpose? a) CyclicBarrier b) CountDownLatch c) Exchanger d) Semaphore

42 Quiz #6 > You want to allow no more than 4 active file downloads at a time. If one download is paused, that should allow another download to become active. If the user resumes a paused download, that download has to wait to actually resume until only 3 are currently active so as to not exceed the limit of 4 active downloads. Which Synchronizer is best suited for this purpose? a) CyclicBarrier b) CountDownLatch c) Exchanger d) Semaphore Quiz #7 > You have several threads, each updating the position of a character in a 3D world. You don t want a thread to start processing the next frame until all other threads have finished processing the previous frame. Which Synchronizer is best suited for this purpose? a) CyclicBarrier b) CountDownLatch c) Exchanger d) Semaphore

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

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

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

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

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

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

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 30: Java Synchronizers, Dining Philosophers Problem Vivek Sarkar, Shams Imam Department of Computer Science, Rice University Contact email: vsarkar@rice.edu,

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

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

Daemon thread, 7 Deadlock, 27

Daemon thread, 7 Deadlock, 27 Index A ArrayBlockingQueue, 127 128 Atomic variables AtomicLong, 132 contention-reduction techniques, 132 counters and sequence generators, 131 getnextid() class, 131 intrinsic lock, 131 java.util.concurrent.atomic

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 30: Advanced locking in Java Vivek Sarkar Department of Computer Science Rice University

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

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

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

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

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

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

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

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

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

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

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

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

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

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

More information

[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

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

[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

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

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

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

-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 330: Organization of Programming Languages

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

More information

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

More information

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

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

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

7. MULTITHREDED PROGRAMMING

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

More information

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

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

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

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions CMSC 433 Programming Language Technologies and Paradigms Fall 2011 Locks & Conditions Intrinsic Lock Example public class RWDictionaryIntrinsicLock { Map m = new TreeMap();

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

Java Barrier Synchronizers: CountDownLatch (Part 1)

Java Barrier Synchronizers: CountDownLatch (Part 1) Java Barrier Synchronizers: CountDownLatch (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

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

Threads and Parallelism in Java

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

More information

Interprocess Communication By: Kaushik Vaghani

Interprocess Communication By: Kaushik Vaghani Interprocess Communication By: Kaushik Vaghani Background Race Condition: A situation where several processes access and manipulate the same data concurrently and the outcome of execution depends on the

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

Java Barrier Synchronizers: CyclicBarrier (Part 1)

Java Barrier Synchronizers: CyclicBarrier (Part 1) Java Barrier Synchronizers: CyclicBarrier (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

More information

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

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

More information

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

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

More information

Java Semaphore (Part 1)

Java Semaphore (Part 1) Java Semaphore (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning Objectives

More information

Phaser volle Energie...

Phaser volle Energie... Phaser volle Energie...... eine Reise ins Paralleluniversum von JDK7 Hartmut Lang, Ericsson July 2011 Hartmut Lang Senior Software Developer Solution Architect Network Management and Customer Solutions

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

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

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Multithreading Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@stll.au..dk Submission & Peer feedback peergrade.io/join AJJ452 What is going on here? Multithreading Threads

More information

Synchronized Methods of Old Versions of Java

Synchronized Methods of Old Versions of Java Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs next week for a demo time In case you hadn t noticed Classes end Thursday April 15

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

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi

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

Multiple Inheritance. Computer object can be viewed as

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

More information

Concurrent Programming using Threads

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

More information

Concurrent Programming

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

More information

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

Paradigmas de Computação Paralela

Paradigmas de Computação Paralela Paradigmas de Computação Paralela Concurrent/Parallel Programming in OO /Java João Luís Ferreira Sobral jls@... Specification of concurrency/parallelism Benefits from concurrent programming Programs that

More information

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) Dept. of Computer Science & Engineering Chentao Wu wuct@cs.sjtu.edu.cn Download lectures ftp://public.sjtu.edu.cn User:

More information

Models of concurrency & synchronization algorithms

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

More information

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

The Java ExecutorService (Part 1)

The Java ExecutorService (Part 1) The Java ExecutorService (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

Java Threads. COMP 585 Noteset #2 1

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

More information

COMP346 Winter Tutorial 4 Synchronization Semaphores

COMP346 Winter Tutorial 4 Synchronization Semaphores COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated

More information

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples

More information

Synchronizers Latches & Barriers

Synchronizers Latches & Barriers Synchronizers Latches & Barriers Synchronizers A synchronizer is any object that coordinates the control of threads based on its state. The basic mechanisms in java.util.concurrent are: Latches: gate,

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

Dealing with Issues for Interprocess Communication

Dealing with Issues for Interprocess Communication Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed

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

G52CON: Concepts of Concurrency

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

More information

Synchronization COMPSCI 386

Synchronization COMPSCI 386 Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose

More information

The Java FutureTask. Douglas C. Schmidt

The Java FutureTask. Douglas C. Schmidt The Java FutureTask Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning Objectives

More information

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

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

More information

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem Mack Joyner and Zoran Budimlić {mjoyner, zoran}@rice.edu http://comp322.rice.edu

More information

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Brian Goetz Principal Consultant, Quiotix Corp David Holmes Staff Engineer, Sun Microsystems, Inc. TS-4915 2006 JavaOne SM Conference

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

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

Contents. 6-1 Copyright (c) N. Afshartous

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

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

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

More information

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

Principles of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Principles of Software Construction: Objects, Design, and Concurrency The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Fall 2014 Charlie Garrod Jonathan Aldrich School of Computer

More information

Principles of Software Construction: Objects, Design, and Concurrency. Concurrency: More Design Tradeoffs School of Computer Science

Principles of Software Construction: Objects, Design, and Concurrency. Concurrency: More Design Tradeoffs School of Computer Science Principles of Software Construction: Objects, Design, and Concurrency Concurrency: More Design Tradeoffs Christian Kästner Bogdan Vasilescu School of Computer Science 1 2 So far on concurrency Primitives

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

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M) re-exam Concurrent Programming tda383/dit390 Date: 2016-08-22 Time: 14:00 18:00 Place: Maskinhuset (M) Responsible Michał Pałka 031 772 10 79 Result Available no later than 2016-09-12 Aids Max 2 books

More information

G52CON: Concepts of Concurrency

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

More information

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition Module 6: Process Synchronization 6.1 Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

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

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

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

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

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

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

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information