More Multithreaded Programming in Java David Meredith Aalborg University.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems.
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
1Quiz Modify HelloWorld2.java; –Remove (or comment out) the following 4 lines: Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2);
Threads ICW Lecture 10 Tom Chothia. Last Time XML JDOM XPATH.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
50.003: Elements of Software Construction Week 5 Basics of Threads.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Critical Reference An occurrence of a variable v is defined to be critical reference: a. if it is assigned to in one process and has an occurrence in another.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Inter-Thread communication State dependency: Guarded Methods.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
Synchronizing threads, thread pools, etc.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java Thread and Memory Model
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreaded Programming in Java David Meredith Aalborg University.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
1 Java Programming Java Programming II Concurrent Programming: Threads ( II)
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Multithreading / Concurrency
Multithreading.
Slide design: Dr. Mark L. Hornick
Threads Chate Patanothai.
Threads II IS
Condition Variables and Producer/Consumer
Cancellation.
Condition Variables and Producer/Consumer
Java Concurrency 17-Jan-19.
Threads in Java James Brucker.
Threads and Multithreading
Slide design: Dr. Mark L. Hornick
Java Concurrency 29-May-19.
Multithreaded Programming in Java
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

More Multithreaded Programming in Java David Meredith Aalborg University

Sources Chapter 14 of The Java Programming Language (Fourth Edition) by Ken Arnold, James Gosling and David Holmes (Addison- Wesley, 2006) Sun Java Tutorial on Concurrency oncurrency/

Synchronized methods and statements The two code fragments to the right are equivalent In both cases, the object referenced by this is locked while doThis() and doThat() are carried out Remember that this refers to the object on which the method is called public synchronized void myMethod() { doThis(); doThat(); } public void myMethod() { synchronized(this) { doThis(); doThat(); }

Client-side and server-side synchronization Server-side synchronization is where object to be locked takes responsibility for synchronizing code that uses it – often by using a synchronized method Client-side synchronization is where responsibility for synchronizing critical regions of code lies with the code that uses the object to be locked – Means every client has to agree to use synchronized code – Less safe than server-side synchronization – Often done using synchronized statements

Synchronized statements vs. synchronized methods Synchronized statement can protect code region smaller than a whole method Synchronized statement can lock an object other than the one whose method contains the code being protected Allows for holding a lock for as short a time as possible (increases performance) Allows for increasing concurrency by using a finer granularity of locking

Interrupts If b is a Thread, then we interrupt b (“send an interrupt request to b”) by using the message b.interrupt(); If Thread b frequently calls methods that throw InterruptedException (e.g., Thread.sleep()), then the first occurrence of such a method after the interrupt is received will throw an InterruptedException – In this case, we define how the Thread responds to the interrupt in a catch clause (see PingPongRunnable.java) – Usually the run() method will be made to return

Manually responding to an interrupt Sometimes a run() method might not contain any call to a method that throws an InterruptedException In this case, need to regularly check whether the Thread has received an interrupt Using a try-catch clause allows you to centralize the interrupt handling code in one place and separate it clearly from the run code public void run() { for (int i = 0; i < 300; i++) { doSomeCalc(i); if (Thread.interrupted()) { return; } public void run() { for (int i = 0; i < 300; i++) { doSomeCalc(i); if (Thread.interrupted()) { return; } public void run() { try { for (int i = 0; i < 300; i++) { doSomeCalc(i); if (Thread.interrupted()) { throw new InterruptedException(); } } catch (InterruptedException e) { doSomeStuff(); return; } public void run() { try { for (int i = 0; i < 300; i++) { doSomeCalc(i); if (Thread.interrupted()) { throw new InterruptedException(); } } catch (InterruptedException e) { doSomeStuff(); return; }

Interrupt status flag Message, a.interrupt() causes interrupt status flag to be set to true for Thread a If a checks for interrupt status by calling static method, Thread.interrupted(), then interrupt status flag set to false (“cleared”) – Thread a ceases to be in an interrupted state If Thread b wants to know if Thread a has been interrupted, then call a.isInterrupted() from inside b – Does not clear interrupt status flag – That is, if Thread a has been interrupted, it remains in an interrupted state, as indicated by the true value of the interrupt status flag When InterruptedException thrown, interrupt status flag is cleared (i.e., set to false) – thread ceases to be in an interrupted state

The join method The call, t.join(),causes the current Thread to block (i.e., stop doing anything) until Thread t has stopped running The join method throws an InterruptedException if the current Thread is interrupted while it is waiting for another Thread to complete See HrOgFruJensen2.java

SimpleThreads.java

Guarded Blocks A guarded block suspends the current thread until another thread makes some condition become true, which restarts the current thread guardedJoy() method must not execute its last line until the shared variable joy has been made true by some other thread The while loop is keeping the processor busy while it is waiting (busy waiting) – DON’T DO THIS! public void guardedJoy() { while (!joy) {} System.out.println(“Joy has been achieved!”); }

Guarded blocks using wait and notifyAll AchievingJoy.java