Java: Pitfalls and Strategies

Similar documents
This article was first published in the Ada User Journal 23:2 (June 2002)

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Concurrent Programming using Threads

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

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Threads Questions Important Questions

Java Memory Model. Jian Cao. Department of Electrical and Computer Engineering Rice University. Sep 22, 2016

What is a thread anyway?

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

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Multi-threaded programming in Java

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Concurrency in Java Prof. Stephen A. Edwards

Java Threads. Introduction to Java Threads

Note: in this document we use process and thread interchangeably.

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

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

Performance Throughput Utilization of system resources

Java Threads. COMP 585 Noteset #2 1

CS11 Java. Fall Lecture 7

Spinlocks. Spinlocks. Message Systems, Inc. April 8, 2011

CIS233J Java Programming II. Threads

Java Programming Lecture 23

OS06: Monitors in Java

Concurrent Programming

Introduction to Java Threads

Models of concurrency & synchronization algorithms

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

Unit 8: Threads. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

CS 556 Distributed Systems

Two Types of Semaphores

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

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Monitors & Condition Synchronization

Process Synchronization

Concurrent and Real-Time Programming in Java

Synchronization Lecture 23 Fall 2017

Object Oriented Programming and Design in Java. Session 18 Instructor: Bert Huang

Synchronization SPL/2010 SPL/20 1

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Threads and Parallelism in Java

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Animation Part 2: MoveableShape interface & Multithreading

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 2

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

EMBEDDED SYSTEMS PROGRAMMING More About Languages

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

1. Motivation (Race Condition)

Object Oriented Programming. Week 10 Part 1 Threads

System Software Assignment 8 Deadlocks

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

Threads Chate Patanothai

Multithreaded Programming

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Multiple Inheritance. Computer object can be viewed as

The Java Memory Model

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

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

Finding Concurrency Bugs in Java

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

Motivation & examples Threads, shared memory, & synchronization

CMSC 330: Organization of Programming Languages

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

Process Synchronization

7/6/2015. Motivation & examples Threads, shared memory, & synchronization. Imperative programs

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

Synchronization Possibilities and Features in Java

Memory Consistency Models

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Java Threads and intrinsic locks

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

CS 159: Parallel Processing

Internet and Intranet Protocols and Applications

By: Abhishek Khare (SVIM - INDORE M.P)

Techniques of Java Programming: Concurrent Programming in Java

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Interprocess Communication By: Kaushik Vaghani

Results of prelim 2 on Piazza

Java 2 Programmer Exam Cram 2

CS 450 Exam 2 Mon. 4/11/2016

ECE 462 Object-Oriented Programming using C++ and Java. Scheduling and Critical Section

Synchronized Methods of Old Versions of Java

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Relaxed Memory Consistency

Problems with Concurrency. February 19, 2014

Synchronization Lecture 24 Fall 2018

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Basics of. Multithreading in Java

Chapter 6: Process Synchronization. Operating System Concepts 9 th Edit9on

Race Conditions & Synchronization

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

Agenda. Highlight issues with multi threaded programming Introduce thread synchronization primitives Introduce thread safe collections

Transcription:

Java: Pitfalls and Strategies Pao-Ann Hsiung National Chung Cheng University Chiayi, Taiwan Adapted from Bo Sandén, Copying with Java Threads, IEEE Computer, Vol. 37, No. 4, pp. 20-27, April 2004.

Contents 1. Multiple threads, one object 2. Omitting the synchronized keyword 3. Maintaining synchronized blocks 4. Wait loop placement 5. Missing notification of waiting threads 6. Confusing long and short waits

Pitfall #1: Multiple threads, one object Given a class R that implements Runnable 2 ways to create multiple threads executing R s run method: Instantiate R n times, submit each instance once as a parameter to a Thread constructor Own set of instance variables Submit one R n times to Thread s constructor Only one object inconsistencies in object data

Strategy #1: Multiple threads, one object Policy Submit each runnable object to a Thread constructor only ONCE! Compliance checking Include thread creation and start in the constructor new Thread(this).start()

Pitfall #2: Omitting the synchronized keyword Freedom to synchronize selected methods of a class forgotten or purposely unsynchronized methods data inconsistencies Eg: get() synchronized, put() not synchronized Synchronized methods using public variables another method changing the variables without obtaining object lock

Strategy #2: Omitting the synchronized keyword A tool or compiler can identify and flag unsynchronized methods Difficult to spot methods that need to be synchronized

Pitfall #3: Maintaining synchronized blocks Synchronized block a synchronized method declared outside a class may interpret a class as nonsynchronized (whereas it has methods synchronized in some block) may add a method to a class without realizing it needs to be synchronized (due to the block synchronization)

Strategy #3: Maintaining synchronized blocks Prefer synchronized methods to synchronized blocks Exception Coordinating operations on different objects Add comment to a class that has objects synchronized in blocks

Pitfall #4: Wait loop placement (1/2) Wait loop should be written as: while (cond) wait(); object retests cond after reactivation from wait set Variations: while (cond) yield(); // obj lock not released if (cond) wait(); // no retest after reactivation

Pitfall #4: Wait loop placement (2/2) Java allows wait loop to be placed anywhere in a critical section (synchronized method) synchronized void m() { callcounter++; while (cond) wait(); if (callcounter==5) } Data obtained or changed BEFORE wait() Data obtained or changed AFTER wait() Data changed by some other method?

Strategy #4: Wait loop placement Tool or compiler flags incorrect wait() any wait loop that is not the first statement in a synchronized method

Pitfall #5: Missing notification of waiting threads Synchronizations exclusion: automatic (synchronized) condition: not automatic (wait, notify) notify standard Java: arbitrary wait set real-time Java: FIFO wait set notifyall useful when multiple threads can proceed in standard Java, only way to activate highest priority thread in standard and real-time Java, needed when threads pend on different conditions, to be sure of activating one pending on that condition

Strategy #5: Missing notification of waiting threads Code inspection check if all necessary notify, notifyall have been called Time-out parameter in each wait() thread automatically reactivated after time-out checks condition and then proceeds or reenters wait set Does not work for real-time Java!

Pitfall #6: Confusing long and short waits (1/5) Waits: long wait use condition synchronization (wait, notify) short wait use exclusion synchronization (synchronized) Confusion exclusion used where condition required synchronized (f) { // f is a Forklift instance } // spins until f is unlocked, arbitrary access

Pitfall #6: Confusing long and short waits (2/5) synchronized (f) { while (busy) wait(); busy = true; // Operate the forklift busy = false; notify(); } The wait loop has no effect! The thread that sets busy to true also keeps object f locked so no other job that needs forklift can reach the wait loop.

Pitfall #6: Confusing long and short waits (3/5) (a possible solution) f.acquire(); // use f f.release(); synchronized void acquire() { while (busy) wait(); busy = true; } synchronized void release() { busy = false; notify(); }

Pitfall #6: Confusing long and short waits (4/5) (nested critical sections) class V { synchronized void m( ) { synchronized (wo) { while (cond) wo.wait( ) ; } } } if cond is true, the calling thread enters wo s wait set, releases lock on wo, but keeps vo (instance of V) locked, and other threads needing vo spins, instead of waiting in wait set

Pitfall #6: Confusing long and short waits (5/5) (nested critical sections) class V { synchronized void m( ) { synchronized (wo) { while (cond) wait( ); } } } If vo is current instance of V and cond is true, the calling thread enters vo s wait set, and releases its locks on vo, while keeping wo locked!

Strategy #6: Confusing long and short waits Understand the difference between exclusion synchronization (synchronized) condition synchronization (wait, notify) Which to use? no threads no need of exclusion sync remaining constraint use condition sync eg: allocate forklift to one job at a time in sequential implementation too use condition synchronization Tool can flag any wait calls in statically nested critical sections