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

Java and C# in Depth

Exercise Session Week 6

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

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

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

Object Oriented Programming. Week 10 Part 1 Threads

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)

Exercise Session Week 7

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.

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

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

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

Concurrency: a crash course

Threads and Java Memory Model

CS193k, Stanford Handout #8. Threads 3

Programming Language Concepts: Lecture 11

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

Problems with Concurrency. February 19, 2014

Threads and Parallelism in Java

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

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

CS 251 Intermediate Programming Exceptions

Threads & Networking

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

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

Multiple Inheritance. Computer object can be viewed as

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

CS11 Java. Fall Lecture 7

CMSC 330: Organization of Programming Languages

CSC Java Programming, Fall Java Data Types and Control Constructs

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

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

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

CS 159: Parallel Processing

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

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

Concurrency. Fundamentals of Computer Science

Michele Van Dyne MUS 204B Concurrency Issues

Advanced Concepts of Programming

Java Threads and intrinsic locks

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

Introduction to Java Threads

Introduction to Programming Using Java (98-388)

Exception-Handling Overview

Programming in Parallel COMP755

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

COE518 Lecture Notes Week 7 (Oct 17, 2011)

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

Shared Objects & Mutual Exclusion

CS180 Review. Recitation Week 15

Multithreaded Programming

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

CMSC 132: Object-Oriented Programming II

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

Unit III Rupali Sherekar 2017

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

GlobalLogic Technical Question Paper

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

CS 556 Distributed Systems

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

Parallel Programming Practice

Multithreaded Programming

Array. Array Declaration:

Module - 4 Multi-Threaded Programming

Concurrent Programming using Threads

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

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

Parallel Programming Practice

Synchronization in Java

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

Java Platform Concurrency Gotchas

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

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

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

User Space Multithreading. Computer Science, University of Warwick

Java Identifiers, Data Types & Variables

Synchronization SPL/2010 SPL/20 1

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

Info 408 Distributed Applications Programming Exercise sheet nb. 4

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

Parallel Programming Languages COMP360

Java: framework overview and in-the-small features

Program Fundamentals

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Chapter 1 Getting Started

Transcription:

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 http://mreinhold.org/blog/secure-the-train 2

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!» 3

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"); 4

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 5

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

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(); 7

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 8

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

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 10

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 11

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 12

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

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

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

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 16

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

Quiz 8: Thread safe? (Java) Shared data: public static long data; Two threads: Should be declared volatile new Thread(new Runnable() { public void run() { while (true) { data = somefunction(); ).start(); new Thread(new Runnable() { public void run() { while (true) { if (data == target) { dosomething(); ).start(); 18

Java Language Specification 17.7. Non-atomic Treatment of double and long For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write. Writes and reads of volatile long and double values are always atomic. Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values. 19

Quiz 9: 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. 20

Quiz 9: 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. 21

Quiz 9: 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); 22

Questions? 23