Advanced Concepts of Programming

Size: px
Start display at page:

Download "Advanced Concepts of Programming"

Transcription

1 Berne University of Applied Sciences E. Benoist / E. Dubuis January

2 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate threads; Java provides mechanisms for the cooperation of threads. You use a multithreaded program if your program needs to do more than one thing at a time. For instance, load and process a large image file using a background thread while another thread is responsible for user-input responsibility. Threads - 2

3 Examples of use of threads Download a file One thread loads the file, the other work Background Task Some task must answer instantly, it starts other threads that do not stop it. Deamons Web server treats requests as threads. It can handle more than one request at a time.... Threads - 3

4 Sequencial flow of control main MainClass Some Class new amethod some Object JT 1 Threads - 4

5 Standalone program having two threads main MainClass AThread Class new start athread Object run JT 2 Threads - 5

6 The construction of Threads Any class can be used to become a starting point for a thread by extending class java.lang.thread by implementing the java.lang.runnable interface must implement the run method After having created a thread, it accepts only a few methods Threads - 6

7 Extending java.lang.thread import java.lang.thread; public class MyThread extends Thread { // The argument name can be used for debugging public MyThread(String name){ super(name); public void run(){ // Do something here such as creating new objects, // calling methods, perhaps in a never ending loop. // Implicitely called from the start method. Threads - 7

8 Implementing java.lang.runnable The java.lang.runnable interface public interface java.lang.runnable{ public void run(); Write your class import java.lang.runnable; public class MyOtherThread implements Runnable{... public void run(){ //As for class MyThread above. Threads - 8

9 Implementing Runnable is the prefered way The class can be a subclass of any other class than class Thread You do not have to take care with interractions with class Thread Synchronized Methods Threads - 9

10 Starting Threads When Extending java.lang.thread Thread t = new MyThread( aname ); // The thread is started by applying the start method t.start(); When implementing java.lang.runnable // r is the target object of the thread Runnable r = new MyOtherThread(); Thread t = new Thread(r, anothername ); // start the thread t.start; Notice A thread can not be restarted Applying the start() method after termination: java.lang.illegalthreadstateexception Threads - 10

11 Deamon threads Some threads objects have a deamon status Thread t =...; t.setdeamon(true); t.start(); They are immediately terminated after the last non-deamon thread has terminated Threads - 11

12 Thread Priorities Threads are held in priority-based scheduling queues By default, each thread has the priority of the one that created it Priority can be changed: setpriority(). It must stay within Thread.MIN_PRIORITY and Thread.MAX_PRIORITY Threads with higher priority are executed first Priority can be a substitute for locking Threads - 12

13 What do we want Threads to do? Be created Thread t = new Tread(r, anyname ); t.start; Access the current Thread (since this is not a thread) Thread.currentThread Sleep durring some time Thread.sleep(10000);// milliseconds Wait for a ressource to be free Let other threads to possibility to be executed Thread.yield()... Threads - 13

14 Problems with Treads Accessing the memory A value can be accessed simultaneously by many threads If they increment it how many increment will be done? Access and updates of memory cells are: not atomic for long and double atomic (can not be devided) for any other type long and double can be atomic if defined as volatile: public class Measurment { private volatile long index; private volatile double value; Some methods should only be used by one only Thread Threads - 14

15 Thread Life Cycle I new JT 3 New Dead start exit run yield sleep Runnable time el., interrupt wait notify, notifyall, interrupt blocking, locking, join unblocking, unlocking, return from join interrupt Not Runnable Threads - 15

16 Stopping Threads Stopping Threads Using Some Variable public class SomeThread extends Thread{ private volatile boolean done; //... public void run(){ // perhaps make some initialization first while (! done) { // do something // Perhaps do some cleaning up Threads - 16

17 Stopping Threads Using Some Variable The place where the checking of the condition is performed repeatedly guarantees that the thread cannot hold any lock at this place. Thus, if the thread is about to stop, then it is guaranteed that It does not hold any lock and thus has left any sychnonized methods How to change the value a method for falsifying the condition // In SomeThread class public void terminate(){ done = true; Threads - 17

18 Thread.interrupt We call this method on a target thread: // In the body of some method Runnable r =... Thread t = new Thread(r); // then later t.interrupt() Threads - 18

19 Thread.interrupt II Effect if the thread is runnable Its interruption status is set to true The thread has to check its interruption status periodically public class SomeThread implements Runnable{ public void run(){ // perhaps make some initialization first. while(! Thread.currentThread().isInterrupted()){ // Do something // perhaps do some cleaning Threads - 19

20 Thread.interrupt III If the thread is blocked on methods: Object.wait, Thread.sleep, Thread.join the actions throw an InterruptedException and t s interruption status is set to false public class SomeThread implents Runnable{ public void run(){ while( cond &&!Thread.currentThread().isInterrupted()){ //Do something then try{ Thread.sleep(10000); catch (InterruptedException e){ //Perhaps do some cleaning up return; // Cond becomes false after a while... Threads - 20

21 Mutual Exclusion of Threads Let us consider 2 threads incrementing an object (implementing interface IntContainer ) :IntContainer incr() incr() incr1 incr1 Threads - 21

22 IntContainers Interface and Implementations Interface can have many implementations having different behaviours public interface IntContainer { public void incr(); public void read(); Very easy class class IntContainer1 implements Container { private int n=0; public void incr() { n++; public int read() { return n; Threads - 22

23 A thread incrementing the object public class Incr implements Runnable { private int m; private IntContainer n; public Incr(IntContainer n, int m){ this.m = m; this.n = n; public void run() { for (int i = 0; i < m; i++) { n.incr(); Threads - 23

24 Let s create two threads and start them IncContainer n = new IntContainer1(); Thread incr1 = new Thread(new Incr(n,m)); Thread incr2 = new Thread(new Incr(n,m)); incr1.start(); incr2.start(); try { incr2.join(); incr1.joint(); catch(interruptedexception e) { return; if (n.read() == 2 m) { System.out.println( Value n is Correct: + n.read() +. ); else { System.out.println( Value n is too SMALL: + n.read() +, it should be: + 2 m +. ); Threads - 24

25 Let s create two threads and start them Output is something like: > java Increment Value n is too SMALL: 10745, it should be: Threads - 25

26 Reason Thread incr1 Thread incr2 Case: n = 60 LOAD n The value 60 is now in the register of this thread this thread does something else ADD 1 Register contains 61 LOAD n the value 60 is in the register of this thread STORE n the value 61 is stored in ADD1 register contains 61 memory location n this thread does something else STORE n the value 61 is stored in memory location n, the old value, 61, is overridden n = 61, instead of 62 Threads - 26

27 Volatile variables may help? The introduction of the volatile modifier does not help either class IntContainer2 implements IntContainer { private volatile int n = 0 ; public void incr() { n++; // n++ operation is not atomic public int read() { return n; Threads - 27

28 Next Improvement incr() should not be executed by more than one thread It is the critical section. There must be mutual exclusion in the body of incr() The synchrinized modifier of methods public synchronized void incr(){ n++; Corresponds to the following pseudo-code // Body of incr, Acquire lock or wait until lock is available; n++ Release lock; A thread remains there until the lock becomes available. Upon unlocking an object by a thread, all other threads wanting the lock of that particular object are put back into the Runnable state, ready for thread scheduling. Threads - 28

29 When Using synchronized Methods Let s modify the integer container class IntContainer3 implements IntContainer { private int n; public synchronized void incr(){ n++; public int read() { return n; Output: > java Increment Value n is CORRECT: Threads - 29

30 Remarks on IntIncrement3 read returns the current value of the int Synchronization is not necessary since read of int value is atomic. If the value were long then read should either be synchronized, or the field should be volatile. If the value were an array or an object composition, then a synchronized would be mandatory. Threads - 30

31 Further Notes on Synchronization It is sometime more performing to acquire the lock for only a part of the body of a method: // Some method s body... synchronized(this) { other statements;... Or, the exclusive access of another object is necessary within a statement sequence: // Some method s body... synchronized(anotherobject) { anotherobject.somemethod(); Threads - 31

32 Java monitors are reentrant A synchronized method can be called from within a synchronized method Once acquired the lock, a thread calling another method of the already locked object does not block. Two methods of the class: public synchronized void a() { this.b(); // Does not block, has lock already public synchronized void b() {... Threads - 32

33 Notes on Synchronization Non-sychronized methods can be executed by any thread at any time class X { void a() {... synchronized void b() {... synchronized void c() {... (a,b) and (a,c) can be executed non-exclusively! However (b,c) is not possible! Execution penalty when using synchronization Synchronizing methods makes the program safier It is a costly operation Threads - 33

34 Conditionally synchronizing threads I Threads must cooperate To let them cooperate, shared objects are used The progress of a thread may depend on the progress of others One key abstraction often used in such a context is the one of a Buffer public abstract class Buffer { public void put(object x) throws InterruptedException; public Object get() throws InterruptedException; Threads - 34

35 Conditionally synchronizing threads II Considere a Producer/Consumer relation Producer: public class Producer implements Runnable { private Buffer buffer; public void run() { Integer item = null; for (int i = 0; i < 10; i++) { // Compute new item. buffer.put(item); Threads - 35

36 Conditionally synchronizing threads III Consumer public class Consumer implements Runnable { private Buffer buffer; public void run() { Integer item = null; for (int i = 0; i < 10; i++) { item = (Integer) buffer.get(); // Do something, e.g., print the value of the item Threads - 36

37 Conditionally synchronizing threads IV Both threads are using a OnePlaceBuffer1 class OnePlaceBuffer1 extends Buffer { private Object content; public synchronized void put(object x) throws InterruptedException { content = x; // Pint statements for testing purpose public synchronized Object get() throws InterruptedException { return content; // Print statement for testing purpose Threads - 37

38 Tests Creating a OnePlaceBuffer1 object and the two threads (n=5) > java test.oneplacebuffertest1 5 consumes: null, Produces: 0, Produces: 1, consumes: 1, consumes: 1, Produces: 2, consumes: 2, consumes: 2, Produces: 3, consumes: 3, Produces: 4 Remarks null has been fetched before something has been produced 1 has been stored before 0 has been fetched 4 has never been consumed There must be a way to coordinate threads! Threads - 38

39 Waiting on Conditions to Happen Slow down the Producer or the Consumer to work together // Pseudo java private boolean empty = true; public synchronized void put(object x) throws InterruptedException { while (!empty) { wait until the value has been consumed empty = false; contents = x; public synchronized Object get() throws InterruptedException { while(empty) { wait until a value has been produced; empty = true; return contents; Threads - 39

40 1.4 Threads - 40

41 slidesthreads.tex Threads - 41

42 ======= Coordinate threads This is called condition synchronization How should the bodies of the while loops be implemented? Specific methods of the class Object. wait() The current thread releases the lock of this object and waits (going into thread state NotRunnable). The thread is added to the object s wait set. It waits there until being notified by another thread. wait(millisec) and wait(millisec, nanosecs) The current thread releases the lock of this object and waits (going to the state NotRunnable). The thread is added to the object s wait set. It waits there until being notified by another thread, or the time-out period has elapsed. The second form allows finer control for specifying the time to wait. Every object has an associated wait set. Threads - 42

43 Coordinate threads (Cont.) private boolean empty = true; public synchronized void put(object x) throws InterruptedException { while (!empty) { try{ this.wait(); catch (InterruptedException e){ throw e; empty = false; content = x; public synchronized Object get() throws InterruptedException { while(empty) { try{ this.wait(); catch (InterruptedException e){ throw e; empty = true; return content; Threads - 43

44 Dead Lock Output > java test/oneplacebuffertest2 Produces: 0 Produces: 1 ˆC Observations of this particular run 1. Producer produces item 0 and puts it into the buffer. 2. Producer produces item 1 then it blocks. 3. Consumer consumes item Consumer wants to consumed item 1 then it blocks. 5. Both threads are waiting. This is a Dead Lock Threads - 44

45 Notifying another thread to Unlock from the Wait Set The previous version Dead Locks. There is no thread which notifies any of the threads once added to the wait set. The notify family of methods notify() The current threads wakes up an arbitrary, single thread That thread enters the Runnable state It is ready for thread scheduling (of course it can not go one if the current thread does not relinquishes the object s lock) notifyall() wakes up all the threads of the wait set they become Runnable and are ready for scheduling. Threads - 45

46 Notifying To fix our problem, every thread notifies the other to resume. private boolean empty = true; public synchronized void put(object x) throws InterruptedException{ while (! empty){ try { this.wait(); catch (InterruptedException e) { throw e; empty = false; content = x; this.notify(); Threads - 46

47 Notify for get Similarly, for the get method public synchronized Object get() throws InterruptedException{ while (empty){ try { this.wait(); catch (InterruptedException e){ throw e; empty=true; this.notify(); return content; Threads - 47

48 Output > java test.oneplacebuffertest3 Produces: 0 consumes: 0 Produces: 1 consumes: 1 Produces: 2 consumes: 2 Produces: 3 consumes: 3 Produces: 4 consumes: 4 It works! Threads - 48

49 When having n Producers and Consumers 10 producers and 10 consumers each handling 5 items A particular run could be >java OnePlaceBufferTest4 prodcnt 10 conscnt 10 5 Produces: 0, consumes: 0, Produces: 0, consumes: 0 Produces: 0,... consumes: 3, Produces: 2, consumes: 2, Produces: 2 ˆC It sometimes deadlocks Suppose : one producer and 10 consumer in the wait set Another producer produces an item and stores it It makes a notify but unfortunately wakes up the only producer waiting The buffer is full and all consumers are waiting Dead Lock! Threads - 49

50 Improvement using a notifyall() I private boolean empty = true; public synchronized void put(object x) throws InterruptedException{ while (! empty){ try { this.wait(); catch (InterruptedException e) { throw e; empty = false; content = x; this.notifyall(); Threads - 50

51 Improvement using a notifyall() II public synchronized Object get() throws InterruptedException{ while (empty){ try { this.wait(); catch (InterruptedException e){ throw e; empty=true; this.notifyall(); return content; Threads - 51

52 Output Having 10 producers and 10 consumers, each handling 5 items >java OnePlaceBufferTest4 prodcnt 10 conscnt 10 5 Produces: 0 consumes: 0 Produces: 0 consumes: 0 Produces: 0... consumes: 4 Produces: 4 consumes: 4 Threads - 52

53 Suspending Threads There are two methods for stopping and restarting threads suspend() resume() What is the problem with Thread.suspend the thread immediately suspends its execution It does not release any of the locks it holds Other threads are still blocked Both suspend() and resume() are deprecated. The programmer should introduce variables and check them repeatedly We use a variable suspended When it is true, we wait() The thread is resumed when it receves a notify() Threads - 53

54 Suspending Threads : The Safe Way // In some class extending Thread or implementing Runnable private boolean suspended; public void run() { while (continue) { // The following must be in a try clause. try { // check first if thread can continue. if (suspended) { synchronized (this) { while (suspended) { this.wait(); catch (InterruptedException ex) { return; // Do something usefull here. Threads - 54

55 Suspending Threads : The Safe Way II We need methods to set the value of suspended public void hold() { suspended = true; public synchronized void release(){ suspended = false; this.notify(); 1.4 Java requires that notify() (and notifyall()) be only in synchronized methods or blocks. It avoids race conditions whcih can occure if notifications can occur sumultaneously with the application of wait methods. Threads - 55

56 Bibliography Doug Lea, Concurent Programming in Java, second edition, Addison Wesley, 2000, ISBN See also: Joshua Block, Effective Java Programming Language Guide, Addison Wesley, 2001, ISBN Why are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Depracated?, threadprimitivedeprecation.html Threads - 56

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

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

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

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

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

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

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

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

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

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

Programming Language Concepts: Lecture 11

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

More information

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

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

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

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

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

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

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

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

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

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

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

Java Threads. Written by John Bell for CS 342, Spring 2018

Java Threads. Written by John Bell for CS 342, Spring 2018 Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.

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

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

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

CS 556 Distributed Systems

CS 556 Distributed Systems CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that

More information

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Reading from URL. Intent - open URL  get an input stream on the connection, and read from the input stream. Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)

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

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

More information

Concurrency in Java Prof. Stephen A. Edwards

Concurrency in Java Prof. Stephen A. Edwards Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for

More information

Unit - IV Multi-Threading

Unit - IV Multi-Threading Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first

More information

Problems with Concurrency. February 19, 2014

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

More information

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

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

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

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

Multithread Computing

Multithread Computing Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread

More information

CS193k, Stanford Handout #8. Threads 3

CS193k, Stanford Handout #8. Threads 3 CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current

More information

Multithreading in Java Part 2 Thread - States JAVA9S.com

Multithreading in Java Part 2 Thread - States JAVA9S.com Multithreading in Java Part 2 Thread - States By, Srinivas Reddy.S When start() method is invoked on thread It is said to be in Runnable state. But it is not actually executing the run method. It is ready

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

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

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

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University Threads & Timers CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Multi-tasking When you re working, how many different applications do you have open at one

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

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar Design Patterns MSc in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie)! Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking) What is a Thread? 2 THREADS AND CONCURRENCY A separate process that can perform a computational task independently and concurrently with other threads Most programs have only one thread GUIs have a separate

More information

public class Shared0 { private static int x = 0, y = 0;

public class Shared0 { private static int x = 0, y = 0; A race condition occurs anytime that the execution of one thread interferes with the desired behavior of another thread. What is the expected postcondition for the following bump() method? What should

More information

RACE CONDITIONS AND SYNCHRONIZATION

RACE CONDITIONS AND SYNCHRONIZATION RACE CONDITIONS AND SYNCHRONIZATION Lecture 21 CS2110 Fall 2010 Reminder 2 A race condition arises if two threads try and share some data One updates it and the other reads it, or both update the data

More information

Chapter 19 Multithreading

Chapter 19 Multithreading Chapter 19 Multithreading Prerequisites for Part VI Chapter 14 Applets, Images, and Audio Chapter 19 Multithreading Chapter 20 Internationalization 1 Objectives To understand the concept of multithreading

More information

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

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

More information

Synchronization synchronization.

Synchronization synchronization. Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two

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

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

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico. Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing

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

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

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads Concurrency - Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads 1 Introduction Concurrency can occur at four levels: Machine instruction

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

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

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

Synchronization in Java

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

More information

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC Contents G53SRP: Java Threads Chris Greenhalgh School of Computer Science 1 Definition Motivations Threads Java threads Example embedded process Java Thread API & issues Exercises Book: Wellings 1.1 &

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

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

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

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

More information

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics

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

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

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006 This document provides a brief introduction to programming with threads in Java. I presume familiarity

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

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Java implementations of concurrency process and threads

More information

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

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

More information

Object Oriented Programming (II-Year CSE II-Sem-R09)

Object Oriented Programming (II-Year CSE II-Sem-R09) (II-Year CSE II-Sem-R09) Unit-VI Prepared By: A.SHARATH KUMAR M.Tech Asst. Professor JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, HYDERABAD. (Kukatpally, Hyderabad) Multithreading A thread is a single sequential

More information

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico March 17, 2016 CPD (DEI / IST) Parallel and Distributed

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

Faculty of Computers & Information Computer Science Department

Faculty of Computers & Information Computer Science Department Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process

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

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University Concurrent Programming Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University 1 Objectives You will learn/review: What a process is How to fork and wait for processes What a thread is How to spawn

More information

Threads Questions Important Questions

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

More information

CS 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

Advanced Programming Concurrency

Advanced Programming Concurrency Advanced Programming Concurrency Concurrent Programming Until now, a program was a sequence of operations, executing one after another. In a concurrent program, several sequences of operations may execute

More information

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Unit 4. Thread class & Runnable Interface. Inter Thread Communication Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more

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

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004 Thread Programming Comp-303 : Programming Techniques Lecture 11 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 11 Comp 303 : Programming Techniques Page 1 Announcements

More information

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal Java Threads What is a Thread? Individual and separate unit of execution that is part of a process multiple threads can work together to accomplish a common goal Video Game example one thread for graphics

More information

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture 2 Concurrency Model checking Java Pathfinder (JPF) Detecting race condition Bounded buffer problem

More information

COE518 Lecture Notes Week 7 (Oct 17, 2011)

COE518 Lecture Notes Week 7 (Oct 17, 2011) coe518 (Operating Systems) Lecture Notes: Week 7 Page 1 of 10 COE518 Lecture Notes Week 7 (Oct 17, 2011) Topics multithreading in Java Note: Much of this material is based on http://download.oracle.com/javase/tutorial/essential/concurrency/

More information

Reintroduction to Concurrency

Reintroduction to Concurrency Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking

More information

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

wait with priority An enhanced version of the wait operation accepts an optional priority argument: wait with priority An enhanced version of the wait operation accepts an optional priority argument: syntax: .wait the smaller the value of the parameter, the highest the priority

More information

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that

More information

CS180 Review. Recitation Week 15

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

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

Definition: A thread is a single sequential flow of control within a program.

Definition: A thread is a single sequential flow of control within a program. What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread

More information

Software Practice 1 - Multithreading

Software Practice 1 - Multithreading Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee

More information

Java s Implementation of Concurrency, and how to use it in our applications.

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

Concurrency COMS W4115. Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science

Concurrency COMS W4115. Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science Concurrency COMS W4115 Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science Concurrency Multiple, simultaneous execution contexts. Want to walk and chew gum at the same

More information

Implementing Coroutines. Faking Coroutines in Java

Implementing Coroutines. Faking Coroutines in Java Concurrency Coroutines Concurrency COMS W4115 Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science Multiple, simultaneous execution contexts. Want to walk and chew gum

More information