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

Size: px
Start display at page:

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

Transcription

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

2 Using Threads - All the computer programs you've seen so far were sequential only one thing was performed at any given time - Sometimes it is desirable to do several things simultaneously (when?) Multitasking vs. Multithreading - If the tasks to be performed are not related in any way, using a different process for each task is a good solution - If the tasks are somewhat related, and need to share data between them, it is beneficial to put them inside the same process, so they can share resources. This is achieved using Threads - Several Threads can run simultaneously on a single process, sharing its resources. Special care should be taken when using those shared resources

3 How to use Threads in Java In order to run a task in parallel, two steps should be taken: 1. Define the task: - Defining the task is done by implementing the Runnable interface: class SomeClass implements Runnable { public void run() { some code Ask "someone" to run it: - Option 1: Use Executor - Option 2: Create Threads

4 Step 1 - (Define the task) example (code of PS4 on SPL site): class SimpleRunnable implements Runnable { private int m_number; public SimpleRunnable(int i) { this.m_number = i; public void run() { for (int i = 0; i < 10; i++) { System.out.print (" " + m_number);

5 Step 2 - (Run the task) - example 1 (Use Executor): public class Threads01e { public static void main(string[] a) { // Create an executor: ExecutorService e = Executors.newFixedThreadPool(3); // create several runnables, and execute them. for (int i=0; i < 10; i++) { System.out.println("creating a new task: " + i + " "); SimpleRunnable r = new SimpleRunnable(i); e.execute(r); e.shutdown(); // this causes the executor not to accept any // more tasks, and to kill all of its threads // when all the submitted tasks are done. What will this code print?

6 Step 2 - (Run the task) - example 2 (Create Threads): public class Threads01 { public static void main(string[] a) { SimpleRunnable r1 = new SimpleRunnable(1); Thread t1 = new Thread(r1); SimpleRunnable r2 = new SimpleRunnable(2); Thread t2 = new Thread(r2); t1.start(); t2.start();

7 Threads can be Dangerous - Having things run "at the same time, in the same place", can be dangerous. - The two tasks can interfere with each other, and unexpected results might occur. - Printer example - Even example

8 Printer example class Printer { Printer() { public void printaline(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) { System.out.print(s); System.out.println(); class SimpleAsynchronousTask implements Runnable { Printer m_p; String m_name; SimpleAsynchronousTask(String name, Printer p) { m_p = p; m_name = name; public void run() { for (int i = 0; i<50; i++) { m_p.printaline(i, m_name); public class Threads02 { public static void main(string[] a) { Printer p = new Printer(); Thread t1 = new Thread( new SimpleAsynchronousTask("a", p) ); Thread t2 = new Thread( new SimpleAsynchronousTask("b", p) ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb

9 Even example class Even { private long n = 0; public long next() { n++; class EvenTask implements Runnable { Even m_even; EvenTask(Even even) { m_even = even; try {Thread.sleep(30); catch (InterruptedException e) { n++; return n; public void run() { for (int i = 0; i < 50; i++) { System.out.println(m_even.next()); public class Threads03 { /** * Demonstrating the failing of the pre/post conditions of Even. */ public static void main(string[] args) { ExecutorService e = Executors.newFixedThreadPool(10); Even ev = new Even(); for (int i=0; i<10; i++) { e.execute(new EvenTask(ev)); e.shutdown();

10 Even 2 - example class Even { private long n = 0; public long next() throws NotEvenException { if (n%2!= 0) { throw new NotEvenException("PRE:not even"); n++; try {Thread.sleep(30); Catch (InterruptedException e) { n++; if (n%2!= 0) { throw new NotEvenException("POST:not even"); return n; public class Threads04 { /** * Demonstrating the failing of the pre/post conditions of Even. */ public static void main(string[] args) { ExecutorService e = Executors.newFixedThreadPool(10); Even ev = new Even(); for (int i=0; i<10; i++) { e.execute(new EvenTask(ev)); e.shutdown();

11 Safety Running several threads in parallel is not safe. Unpredictable results on shared resources.

12 Design approaches towards avoiding safety problems Thread confinement Immutability Locking / Synchronization

13 Shared Resources A shared resource is any object that is visible to several threads. This includes: global (static) objects, non-primitive method parameters and class members, but not local function variables. Objects that may be visible to several threads - Are not safe. Objects that cannot be shared (local function variables) - Are safe.

14 class Foo{ public static double NUMBER = 33.3; class ClassA { public long i; public Vector v; public ClassA (){/* */ public void dosomething(long x, List lst){ long localvar = 0; Object o; o = this.v.elementat(2); // 1 localvar += 2; // 2 this.i += 2; // 3 x += 2; // 4 lst.elementat(2); // 5 Foo.NUMBER = 4; // 6 localvar = Foo.NUMBER; // 7

15 class TaskA implements Runnable { private ClassA a; private List lst; public long r; // some code. public void run(){ this.r = 2; // 8 this.a.dosomething(9,lst); // 9 class Main { public static void main(string[] args){ ClassA o1 = new ClassA(); Thread t1 = new Thread(new TaskA(o1)); t1.start(); // some code.

16 class Foo{ public static double NUMBER = 33.3; class ClassA { public long i; public Vector v; public ClassA (){/* */ public void dosomething(long x, List lst){ long localvar = 0; Object o; o = this.v.elementat(2); // 1 - Accessing a public member variable. localvar += 2; // 2 this.i += 2; // 3 - Accessing a public member variable. x += 2; // 4 lst.elementat(2); // 5 - Accessing a possible shared object (lst). Foo.NUMBER = 4; // 6 - (never safe!) localvar = Foo.NUMBER; // 7 - (never safe!)

17 class TaskA implements Runnable { private ClassA a; private List lst; public long r; // some code. public void run(){ this.r = 2; // 8 - Accessing a public member variable. this.a.dosomething(9,lst);// 9 - The private member variable (lst) is exposed to class A. class Main { public static void main(string[] args){ ClassA o1 = new ClassA(); Thread t1 = new Thread(new TaskA(o1)); t1.start(); // some code.

18 Thread Confinement A resource that is used exclusively by a one single thread is confined to the thread. If all the resources of a method are confined, then it is safe.

19 createcar() method is confined, and so the method is safe to use in a multi-threaded situation public class ThreadConfinedExample { //ThreadConfined public Car createcar() { Engine e = new FuelEngine(); List<Door> doors = new LinkedList<Door>(); doors.add(new FrontDoor()); doors.add(new FrontDoor()); doors.add(new BackDoor()); doors.add(new BackDoor()); Radio r = new AMFMRadio(); Car c = new Car(e, doors, r); return c;

20 Why is this createcar(engine e) method not safe? public class ThreadNotConfinedExample { //NotThreadConfined public Car createcar(engine e){ List<Door> doors = new LinkedList<Door>; doors.add(new FrontDoor()); doors.add(new FrontDoor()); doors.add(new BackDoor()); doors.add(new BackDoor()); Radio r = new AMFMRadio()); Car c = new Car(e, doors, r); return c;

21 Immutability An immutable object s state cannot be changed after construction. Thus, it can be safely used as a read-only object by multiple threads Examples (classes in Java that are immutable): String Integer

22 mutable class (not safe - why?) immutable class public class Colors { private int c1; private String name; final public class Colors { //final class final private int c1; //final, private fields final private String name; public Colors(int c1, String name) { this.c1 = c1; this.name = name; public Colors(int c1, String name) { this.c1 = c1; //primitive this.name = name; //String is immutable public int getcolor() { return c1; public int getcolor() { return c1; public String getname() { return name; public String getname() { return name; public void change(int c1, String name) { this.c1 = c2; this.name = name; public Colors change(int newc, String newname) { Return new Colors(newC, newname);

23 An object is immutable if: Immutability All primitive fields are final. All other fields are references to immutable objects. The object is immutable only after it has been safely published The object has been safely published if: Reference to this hasn't escaped during construction. No thread has accessed the object before the construction completed.

24 this escape example Public class ClassA {... public void setb(classb objb) { Public class ClassB {... //constructor public ClassB(ClassA obja){... obja.setb(this);...

25 Immutability - It is not always possible to make all your fields immutable, but, you can still get the immutability effect! A class will be immutable if all of the following are true: 1. All of its fields are final 2. The class is declared final 3. The this. reference is not allowed to escape during construction 4. Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes: Are private Are never returned or otherwise exposed to callers Are the only reference to the objects that they reference Do not change the state of the referenced objects after construction

26 Example: immutable class, that consists of mutable objects //The class is immutable due to its design, not just by using the final keyword. //After the class instance is constructed, it becomes read-only by design public final class ThreeStooges { //final class can't have subclasses private final Set<String> stooges = new HashSet<String>(); //final here means it won't be assigned with another reference public ThreeStooges() { stooges.add("moe"); //but still the object stooges is mutable: //its internal values may change stooges.add("larry"); stooges.add("curly"); public boolean isstooge(string name) { return stooges.contains(name);

27 Summary The most useful policies for using and sharing objects in a concurrent program are: Thread-confined - A thread-confined object is owned exclusively by and confined to one thread, and can be modified only by the thread that owns it Shared read-only - A shared read-only object can be accessed concurrently by multiple threads without additional synchronization, but cannot be modified by any thread. Shared readonly objects are immutable. Shared thread-safe - A thread-safe object performs synchronization internally, so multiple threads can freely access it through its public interface without further synchronization.

28 System Programming Practical Session 5: Synchronization

29 Synchronization A mechanism allowing safely accessing shared resources. A thread accessing a synchronized method locks the object. The object cannot be accessed by other threads while it is locked.

30 Synchronization Class Even{ private long n = 0; public long next(){ n++; n++; return n;

31 Synchronization Synchronize a method: - The object on which it is invoked acts as the synchronization "key". - The key is acquired when entering the method, and is released one leaving it. Who is the key? Class Even{ private long n = 0; public synchronized long next(){ n++; n++; return n;

32 Synchronizing a block In this case, you have to implicitly specify the synchronization object Who is the key? public int foo() { // do something safe synchronized(this) { // do something return 9;

33 - The word "synchronized" doesn't automatically make the code thread safe - Good programming uses the minimal amount of Synchronization

34 Solution to safety problem Printer Example (from practical session 1) Where do we synchronize? class Printer { Printer() { /** i line number s the string to concatenate 40 times */ public void printaline(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) { System.out.print(s); System.out.println();

35 public class GoodSynchronization{ public static void main(string[] a) { Printer p = new Printer(); Thread t1 = new Thread( new SimpleAsynchronousTask("a", p) ); Thread t2 = new Thread( new SimpleAsynchronousTask("b", p) ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb class SimpleAsynchronousTask implements Runnable { Printer m_p; String m_name; public SimpleAsynchronousTask(String name, Printer p) { m_p = p; m_name = name; public void run() { for (int i = 0; i < 50; i++) { m_p.printaline(i, m_name);

36 class Printer { Printer() { /** i line number s the string to concatenate 40 times */ public synchronized void printaline(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) { System.out.print(s); System.out.println();

37 Wrong solution #1 Why? public class BadSynchronization2 { public static void main(string[] a) { Printer p1 = new Printer(); Printer p2 = new Printer(); Thread t1 = new Thread( new SimpleAsynchronousTask("a", p1) ); Thread t2 = new Thread( new SimpleAsynchronousTask("b", p2) ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb class SimpleAsynchronousTask implements Runnable {...the same like GoodSynchronization.java class Printer {...the same like GoodSynchronization.java

38 Wrong solution #2 (no printer object) Why? class BadSynchronization { public static void main(string[] a) { Thread t1 = new Thread( new SimpleAsynchronousTask("a") ); Thread t2 = new Thread( new SimpleAsynchronousTask("b") ); t1.start(); // prints some lines of aaaa t2.start(); // prints some lines of bbbb class SimpleAsynchronousTask implements Runnable {...the same like GoodSynchronization.java public synchronized void printaline(int i, String s) { System.out.print(i + ") "); for (int j = 0; j < 40; j++) System.out.print(s); System.out.println();

39 Summary The most useful policies for using and sharing objects in a concurrent program are: Thread-confined - A thread-confined object is owned exclusively by and confined to one thread, and can be modified only by the thread that owns it Shared read-only - A shared read-only object can be accessed concurrently by multiple threads without additional synchronization, but cannot be modified by any thread. Shared readonly objects are immutable. Shared thread-safe - A thread-safe object performs synchronization internally, so multiple threads can freely access it through its public interface without further synchronization.

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

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

Lecture 17: Sharing Objects in Java

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

More information

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

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

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

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

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions? Project Threads Synchronization Minimum submission Deadline extended to tonight at midnight Early submitters 10 point bonus TSP Still due on Tuesday! Before we begin Plan for today Thread synchronization

More information

Advanced MEIC. (Lesson #18)

Advanced MEIC. (Lesson #18) Advanced Programming @ MEIC (Lesson #18) Last class Data races Java Memory Model No out-of-thin-air values Data-race free programs behave as expected Today Finish with the Java Memory Model Introduction

More information

Introduction to Locks. Intrinsic Locks

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

More information

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

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 Computing CSCI 201 Principles of Software Development

Concurrent Computing CSCI 201 Principles of Software Development Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking

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

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

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

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

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

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

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

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Encapsulation, Publication, Escape Data Encapsulation One of the approaches in object-oriented programming is to use data encapsulation

More information

Safety SPL/2010 SPL/20 1

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

More information

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

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

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

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

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

Concurrency. Fundamentals of Computer Science

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

More information

Question Points Score Total 100

Question Points Score Total 100 Midterm Exam #1 CMSC 433 Programming Language Technologies and Paradigms Spring 2014 March 13, 2014 Guidelines Put your name on each page before starting the exam. Write your answers directly on the exam

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

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

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II) SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics

More information

Java Threads and intrinsic locks

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

More information

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

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

More information

Synchronization SPL/2010 SPL/20 1

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

More information

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

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters. CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.

More information

The Java Memory Model

The Java Memory Model The Java Memory Model What is it and why would I want one? Jörg Domaschka. ART Group, Institute for Distributed Systems Ulm University, Germany December 14, 2009 public class WhatDoIPrint{ static int x

More information

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

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues Michele Van Dyne MUS 204B mvandyne@mtech.edu https://katie.mtech.edu/classes/csci136 Concurrency Issues Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core)

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Synchronization in Java Department of Computer Science University of Maryland, College Park Multithreading Overview Motivation & background Threads Creating Java

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

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 Common Java Concurrency pitfalls Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 About me Seasoned software engineer primarily working in the area of Identity and access management. Spent

More information

CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects

CMSC 433 Programming Language Technologies and Paradigms. Sharing Objects CMSC 433 Programming Language Technologies and Paradigms Sharing Objects Administrivia Are you getting your money s worth? Are you reviewing the slides? Are you experimenting with concurrency? Have you

More information

Lecture 9: Introduction to Monitors

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

More information

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

Amity School of Engineering

Amity School of Engineering Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple

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

What is a thread anyway?

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

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

Sharing Objects. Java and Android Concurrency.

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

More information

04-Java Multithreading

04-Java Multithreading 04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org

More information

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

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

Concurrency CSCI 201 Principles of Software Development

Concurrency CSCI 201 Principles of Software Development Concurrency CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Synchronization Outline USC CSCI 201L Motivation for Synchronization Thread synchronization is used

More information

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, Instructions

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, Instructions Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 Name: Athena* User Name: Instructions This quiz is 50 minutes long. It contains 8 pages

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1) Advanced Programming Methods Lecture 6 - Concurrency in Java (1) Overview Introduction Java threads Java.util.concurrent References NOTE: The slides are based on the following free tutorials. You may want

More information

GlobalLogic Technical Question Paper

GlobalLogic Technical Question Paper GlobalLogic Technical Question Paper What is the output of the following code when compiled and run? Select two correct answers. public class Question01 { public static void main(string[] args){ int y=0;

More information

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems

Effective Concurrent Java. Brian Goetz Sr. Staff Engineer, Sun Microsystems Effective Concurrent Java Brian Goetz Sr. Staff Engineer, Sun Microsystems brian.goetz@sun.com The Big Picture Writing correct concurrent code is difficult, but not impossible. Using good object-oriented

More information

Concurrent Programming Lecture 10

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

More information

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.

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

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

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

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

Sharing Objects Ch. 3

Sharing Objects Ch. 3 Sharing Objects Ch. 3 Visibility What is the source of the issue? Volatile Dekker s algorithm Publication and Escape Thread Confinement Immutability Techniques of safe publication Assignment 1 Visibility

More information

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

Multithreading Pearson Education, Inc. All rights reserved.

Multithreading Pearson Education, Inc. All rights reserved. 1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads

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

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING UNIT IV MULTITHREADING AND GENERIC PROGRAMMING Differences between multithreading and multitasking, thread life cycle, creating threads, creating threads, synchronizing threads, Inter-thread communication,

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

Monitors CSCI 201 Principles of Software Development

Monitors CSCI 201 Principles of Software Development Monitors CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Monitors Program USC CSCI 201L Monitor Overview A monitor is an object with mutual exclusion and

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

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. 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 Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

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

More information

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

Speculative Parallelism. Java & Object-Oriented Programming. Reading Assignment

Speculative Parallelism. Java & Object-Oriented Programming. Reading Assignment Speculative Parallelism Prolog also lends itself nicely to speculative parallelism. In this form of parallelism, we guess or speculate that some computation may be needed in the future and start it early.

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

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

Get out, you will, of this bind If, your objects, you have confined

Get out, you will, of this bind If, your objects, you have confined CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREAD SAFETY] Putting the brakes, on impending code breaks Let a reference escape, have you? Misbehave, your code will, out of the blue Get out, you will,

More information

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

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

Access and Non access Modifiers in Core Java Core Java Tutorial

Access and Non access Modifiers in Core Java Core Java Tutorial Access and Non access Modifiers in Core Java Core Java Tutorial Modifiers in Java Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are catagorized into two types,

More information

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below. C212 Early Evaluation Exam Mon Feb 10 2014 Name: Please provide brief (common sense) justifications with your answers below. 1. What is the type (and value) of this expression: 5 * (7 + 4 / 2) 2. What

More information

Advanced concurrent programming in Java Shared objects

Advanced concurrent programming in Java Shared objects Advanced concurrent programming in Java Shared objects Mehmet Ali Arslan 21.10.13 Visibility To see(m) or not to see(m)... 2 There is more to synchronization than just atomicity or critical sessions. Memory

More information

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

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

JAVA - MULTITHREADING

JAVA - MULTITHREADING JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amultithreaded programming language which means we can develop mult it hreaded program

More information

Multithreading. A thread is a unit of control (stream of instructions) within a process.

Multithreading. A thread is a unit of control (stream of instructions) within a process. Multithreading A thread is a unit of control (stream of instructions) within a process. When a thread runs, it executes a function in the program. The process associated with a running program starts with

More information

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION COMP 346 WINTER 2018 1 Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION REVIEW - MULTITHREADING MODELS 2 Some operating system provide a combined user level thread and Kernel level thread facility.

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

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

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