Exercise Session Week 8

Similar documents
Exercise Session Week 8

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Threads Chate Patanothai

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

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

Java and C# in Depth

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer

Exercise Session Week 6

Java Threads. COMP 585 Noteset #2 1

C#: framework overview and in-the-small features

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

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Game Engineering: 2D

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

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

Concurrency: a crash course

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

Threads and Java Memory Model

Exercise Session Week 7

Object Oriented Programming. Week 10 Part 1 Threads

CS193k, Stanford Handout #8. Threads 3

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

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

Problems with Concurrency. February 19, 2014

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

CmpSci 187: Programming with Data Structures Spring 2015

Threads and Parallelism in Java

Threads & Networking

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

Programming Language Concepts: Lecture 11

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Multiple Inheritance. Computer object can be viewed as

CSC Java Programming, Fall Java Data Types and Control Constructs

CMSC 330: Organization of Programming Languages

CS11 Java. Fall Lecture 7

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

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

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

CS 159: Parallel Processing

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

CS 351 Design of Large Programs Threads and Concurrency

7. MULTITHREDED PROGRAMMING

Introduction to Programming Using Java (98-388)

Concurrency. Fundamentals of Computer Science

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

Java Threads and intrinsic locks

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

Michele Van Dyne MUS 204B Concurrency Issues

Introduction to Java Threads

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

Threads are lightweight processes responsible for multitasking within a single application.

CS 251 Intermediate Programming Exceptions

COE518 Lecture Notes Week 7 (Oct 17, 2011)

Shared Objects & Mutual Exclusion

CMSC 132: Object-Oriented Programming II

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

Multithreaded Programming

Advanced Concepts of Programming

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

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

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

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

Exception-Handling Overview

Programming in Parallel COMP755

CS 556 Distributed Systems

Multithreaded Programming

Parallel Programming Practice

CS180 Review. Recitation Week 15

Unit III Rupali Sherekar 2017

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

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Parallel Programming Practice

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Java Identifiers, Data Types & Variables

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

User Space Multithreading. Computer Science, University of Warwick

Java Platform Concurrency Gotchas

Synchronization in Java

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

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

Java: framework overview and in-the-small features

Program Fundamentals

Answer Key. 1. General Understanding (10 points) think before you decide.

Module - 4 Multi-Threaded Programming

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

16-Dec-10. Consider the following method:

Getting started with Java

Concurrent Computing CSCI 201 Principles of Software Development

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

Lecture 9: Introduction to Monitors

Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd)

Java Fundamentals (II)

Transcription:

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 run() { throw new RuntimeException("Help!"); Exceptions from other threads are not propagated to main public static void main(string[] args) { try { (new Thread(new MyTask())).start(); System.out.println("Everything is ok!"); catch (RuntimeException e) { System.out.println("Something went wrong..."); «Everything is ok! Exception in thread...: Help!» 2

Quiz 1: A C# solution In C# you can use asynchronous delegates to propagate exceptions to the main thread: static void MyTask() { throw new Exception("Help!"); delegate void MyTaskInvoker(); public static void Main() { try { MyTaskInvoker method = MyTask; IAsyncResult res = method.begininvoke(null, null); method.endinvoke(res); // This doesn t work: // new Thread(MyTask).Start(); catch (Exception) { Console.WriteLine("Something went wrong"); 3

Quiz 2: What happens (C#)? static void MyTask() { try {... // Some heavy work catch {... finally { Console.WriteLine("Very important cleanup"); public static void Main() { Thread t = new Thread(MyTask); t.isbackground = true; t.start();... t.interrupt(); finally block may not be executed: the main thread may exit before that and the application does not wait for background threads to finish 4

Quiz 3: What can go wrong? (Java) public walkundertherain() { if(!israining) { try { wait(); Shared variable catch (InterruptedException e) { System.out.println("Walking under the rain!"); Don t expect that the first interrupt we get is the one we need: use while instead of if To call wait the enclosing method must be synchronized (otherwise IllegalMonitorStateException is thrown at runtime) 5

Quiz 3: A C# solution: wait handles static EventWaitHandle rain = new AutoResetEvent(false); static void WalkUnderTheRain() { rain.waitone(); Console.WriteLine("Walking under the rain! ); public static void Main() { new Thread(WalkUnderTheRain).Start(); Thread.Sleep(500); rain.set(); 6

Quiz 4.a: What happens? (Java) class MyTask implements Runnable { public void run() { while (true) { public static void main(string[] args) { try { Thread t = new Thread(new MyTask()); t.start(); t.interrupt(); t.join(); run does not handle interrupts System.out.println("t interrupted"); catch (InterruptedException e) { this code will be never executed 7

Quiz 4.a: How to handle interrupts? 1. Calling methods that throw InterruptedException public synchronized void run() { while (true) try { sleep (200); catch (InterruptedException e) { return; 2. Checking Thread.interrupted flag public void run() { while (true) { if (Thread.interrupted()) { return; 8

Quiz 4.b: What happens? (C#) static void Run() { while (true) { public static void Main() { Thread t = new Thread(Run); t.start(); Thread.Sleep(500); t.abort(); t.join(); Console.WriteLine("t aborted"); This code is executed. Unlike Interrupt, Abort stops the thread even if it s currently running 9

Quiz 4.c: What happens (C#)? static void Run() { while (true) { try { Thread.Sleep(1000); catch (ThreadAbortException e) { Console.WriteLine("Ha-ha! I will be executing FOREVER!"); public static void Main() { Thread t = new Thread(Run); t.start(); Thread.Sleep(500); t.abort(); t.join(); Console.WriteLine("t aborted"); Thread t is still aborted! ThreadAbortException is automatically rethrown at the end of the catch block if Thread.ResetAbort is not called 10

Quiz 5: Is this class thread-safe? (Java) class Counter { private int c = 0; public void increment() { c++; public void decrement() { c--; public int value() { return c; Counter count = new Counter;... // In thread 1: count.increment();... // In thread 2: count.increment();... // In the main thread after joining // threads 1 and 2: System.out.println(count.value()); c++ is not atomic => the result might be 1 11

Quiz 5: Is this class thread-safe? (Java) class Counter { private public int c = 0; All attributes must be accessible only through synchronized methods public synchronized void increment() { c++; public synchronized void decrement() { c--; public synchronized int value() { return c; 12

Quiz 5: Is this class thread-safe? (Java) class Counter {... // Everything as before public static synchronized void increment_other(counter other) { other.c++; No: static methods use the class as a lock! Counter(int c) { this.c = c; OK: constructors need not (and cannot) be synchronized, they are executed once per object 13

Quiz 6: What is printed? (Java) public class Test extends Thread { boolean keeprunning = true; public static void main(string[] args) { Test t = new Test(); t.start(); Thread.sleep(1000); t.keeprunning = false; System.out.println("keepRunning is false"); public void run() { while (keeprunning) { System.out.println("finished"); Fix by declaring attributes volatile Thread might cache values locally. Here, it will run forever! 14

Quiz 7: Does it work? (C#) volatile static bool go; volatile static DateTime dt; static void Wait() { while (!go) { Console.WriteLine(dt); public static void Main() { new Thread(Wait).Start(); Thread.Sleep(1000); dt = DateTime.Now; go = true; Here we want to see the change to dt made by the main thread Compilation error: Objects of non-primitive value types cannot be cached by the processor => need not (and cannot) be volatile 15

C# volatile Only (up to) 32bit types can be declared volatile. Reference types (just the reference is volatile) sbyte, byte, short, ushort, int, uint, char, float, bool Threads will always get the most up-to-date value for volatile fields. Fields declared as volatile are not cached. 16

Quiz 8: Communication via Mutex (C#) Given: 1 Mutex 2 Threads that can access only that Mutex How can you transfer data from one thread to the other, using ONLY the Mutex as a communication. 19

Quiz 8: Communication via Mutex (C#) ReleaseMutex WaitOne() Releases the Mutex once. Blocks the current thread until the current WaitHandle receives a signal. (Inherited from WaitHandle.) Return Value: true if the current instance receives a signal. If the current instance is never signaled, WaitOne never returns. WaitOne(Int32) Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval. (Inherited from WaitHandle.) Return Value: true if the current instance receives a signal; otherwise, false. 20

Quiz 8: Communication via Mutex (C#) void SendData(int data) { for (int i = 0; i < 32; i++) { if (((data >> i) & 0x1) == 1) { mutex.waitone(); Thread.Sleep(timeout); mutex.releasemutex(); else { Thread.Sleep(timeout); void ReceiveData() { for (int i = 0; i < 32; i++) { if (mutex.waitone(0)) { mutex.releasemutex(); // bit is 0 else { // bit is 1 Thread.Sleep(timeout); 21

Questions? 22