Thread states. Java threads: synchronization. Thread states (cont.)

Similar documents
Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis

Outline of this lecture G52CON: Concepts of Concurrency

Java Concurrency Framework. Sidartha Gracias

CS11 Java. Fall Lecture 7

8. Condition Objects. Prof. O. Nierstrasz. Selected material 2005 Bowbeer, Goetz, Holmes, Lea and Peierls

Parallel Programming

Deadlock Victim. dimanche 6 mai 12

Unit 6: Conditions, Barriers, and RendezVous

Chapter 6 Concurrent Programming

Java Memory Model: Content

Monitors, Java, Threads and Processes

Lecture 6: Semaphores and Monitors

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

Mutual Exclusion using Monitors

Threads & Tasks: Executor Framework

Java Virtual Machine Locks

Last Class: Semaphores

Monitors & Condition Synchronization

Shared Address Space Computing: Programming

Real Time Programming: Concepts

Concurrent Programming

Chapter 6, The Operating System Machine Level

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

Facing the Challenges for Real-Time Software Development on Multi-Cores

Semaphores and Monitors: High-level Synchronization Constructs

Monitors and Exceptions : How to Implement Java efficiently. Andreas Krall and Mark Probst Technische Universitaet Wien

Threads 1. When writing games you need to do more than one thing at once.

OBJECT ORIENTED PROGRAMMING LANGUAGE

3C03 Concurrency: Condition Synchronisation

How To Write A Multi Threaded Software On A Single Core (Or Multi Threaded) System

Concurrent programming in Java

SYSTEM ecos Embedded Configurable Operating System

Topics. Producing Production Quality Software. Concurrent Environments. Why Use Concurrency? Models of concurrency Concurrency in Java

Thread Synchronization and the Java Monitor

Overview. CMSC 330: Organization of Programming Languages. Synchronization Example (Java 1.5) Lock Interface (Java 1.5) ReentrantLock Class (Java 1.

JAVA - MULTITHREADING

Overview Motivating Examples Interleaving Model Semantics of Correctness Testing, Debugging, and Verification

Performance Improvement In Java Application

aicas Technology Multi Core und Echtzeit Böse Überraschungen vermeiden Dr. Fridtjof Siebert CTO, aicas OOP 2011, 25 th January 2011

Lecture 6: Introduction to Monitors and Semaphores

Linux Scheduler. Linux Scheduler

MonitorExplorer: A State Exploration-Based Approach to Testing Java Monitors

Monitors (Deprecated)

I/O Management. General Computer Architecture. Goals for I/O. Levels of I/O. Naming. I/O Management. COMP755 Advanced Operating Systems 1

Monitors and Semaphores

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Operating Systems Concepts: Chapter 7: Scheduling Strategies

THE UNIVERSITY OF AUCKLAND

Kernel Synchronization and Interrupt Handling

Chapter 2: OS Overview

First-class User Level Threads

OPERATING SYSTEMS PROCESS SYNCHRONIZATION

A Survey of Parallel Processing in Linux

Processes and Non-Preemptive Scheduling. Otto J. Anshus

4. Monitors. Monitors support data encapsulation and information hiding and are easily adapted to an object-oriented environment.

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference.

CS 111 Classes I 1. Software Organization View to this point:

Software and the Concurrency Revolution

Chapter 8 Implementing FSP Models in Java

Thomas Fahrig Senior Developer Hypervisor Team. Hypervisor Architecture Terminology Goals Basics Details

Chapter 11 I/O Management and Disk Scheduling

Thesis Proposal: Improving the Performance of Synchronization in Concurrent Haskell

Distributed Systems [Fall 2012]

Transparent Redirection of Network Sockets 1

6 Synchronization with Semaphores

Centralized Systems. A Centralized Computer System. Chapter 18: Database System Architectures

Java SE 8 Programming

Why Computers Are Getting Slower (and what we can do about it) Rik van Riel Sr. Software Engineer, Red Hat

Lesson Objectives. To provide a grand tour of the major operating systems components To provide coverage of basic computer system organization

Comparison of Concurrency Frameworks for the Java Virtual Machine

Java Interview Questions and Answers

Performance issues in writing Android Apps

A Comparison Of Shared Memory Parallel Programming Models. Jace A Mogill David Haglin

Overview. CISC Developments. RISC Designs. CISC Designs. VAX: Addressing Modes. Digital VAX

Building a Multi-Threaded Web Server

Understanding Hardware Transactional Memory

Embedded Systems. 6. Real-Time Operating Systems

Linux Process Scheduling Policy

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

Comp 204: Computer Systems and Their Implementation. Lecture 12: Scheduling Algorithms cont d

Advanced Multiprocessor Programming

GTask Developing asynchronous applications for multi-core efficiency

1.1. Over view Example 1: CPU Slot Distribution A example to test the distribution of cpu slot.

Optimizing Performance. Training Division New Delhi

Operating System Resource Management. Burton Smith Technical Fellow Microsoft Corporation

Synchronization. Todd C. Mowry CS 740 November 24, Topics. Locks Barriers

CSC 2405: Computer Systems II

Concurrency on the JVM

Using Power to Improve C Programming Education

Keil C51 Cross Compiler

An Introduction to Programming with C# Threads

Chapter 5 Names, Bindings, Type Checking, and Scopes

Storage. The text highlighted in green in these slides contain external hyperlinks. 1 / 14

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Low level Java programming With examples from OpenHFT

System Software and TinyAUTOSAR

Crash Course in Java

Operating Systems 4 th Class

Simple Cooperative Scheduler for Arduino ARM & AVR. Aka «SCoop»

Programming Language Features (cont.) CMSC 330: Organization of Programming Languages. Parameter Passing in OCaml. Call-by-Value

Transcription:

Thread states Java threads: synchronization 1. New: created with the new operator (not yet started) 2. Runnable: either running or ready to run 3. Blocked: deactivated to wait for something 4. Dead: has executed its run method to completion, or terminated by an uncaught exception a started thread is executed in its own run-time context consisting of: program counter, call stack, and some working memory (registers, cache) 1 2 Thread states Thread states (cont.) don't confuse the interface java.lang.runnable with the state Runnable "running" is not a separate state within Runnable, but Thread.currentThread () // static method identifies the current thread object (for itself) thread.isalive () tells if the thread has been started (is not New) and not yet Dead you cannot directly ask whether an alive thread is Runnable or Blocked you cannot directly ask whether a non-alive thread is still New or already Dead 3 4 1

Entering the Blocked state A thread enters the blocked state when: 1. the thread goes to sleep by calling the sleep method 2. the thread calls an operation that blocks until IO operations are complete 3. the thread tries to acquire a lock that is currently held by another thread (mutual exclusion) 4. the thread waits for a condition 5 Transition from Blocked to Runnable A blocked thread moves into the Runnable state when 1. if in sleep, the specified number of milliseconds have been expired 2. if waiting for the completion of an IO operation, the IO operation have finished 3. if waiting for a lock that was owned by another thread, the other thread have released its ownership of the lock 4. if waits for a condition, another thread signals that the condition (may) have changed additionally, can wait for a lock or a condition with a timeout 6 Java Memory Model computers can temporarily hold memory values in registers or local memory caches, and the compiler can reorder instructions to optimize throughput without synchronization, threads (interleaved or parallel) may see out-of-date and/or out-of-order values for the same memory locations locks always ensure that all calculated results are visible to other threads (flushing of caches, etc.) alternatively, you can declare a flag field as volatile: private volatile boolean done;.. public boolean isdone () { return done; a write to a volatile variable synchronizes with all subsequent reads of that same variable (all reads and writes are atomic, even for long and double) 7 Mutual exclusion from critical code basic way to protecting a shared code block: mylock.lock (); // a ReentrantLock object critical section finally { mylock.unlock (); only one thread at a time can enter the critical section (identified and protected by this particular lock) any other threads calling on this lock, are blocked until the first thread unlocks the finally clause makes sure the lock is unlocked even if an exception is thrown 8 2

Fairness you can specify that you want a fair locking policy: Lock fairlock = new ReentrantLock (true); a fair lock favors the thread that has been waiting for the longest time by default, locks are not required to be fair for implementation reasons fair locks can be much slower than regular locks anyway, you have no guarantee that the thread scheduler provided by the plarform is fair so if the thread scheduler neglects a thread, it may not get the chance to be treated fairly by the lock 9 Condition objects a lock protects sections of code, allowing only one thread to execute the code at a time a lock manages threads that are trying to enter a protected code segment a lock can have one or more associated condition objects each condition object manages threads that have entered a protected code section but that cannot proceed for some reason (usually, lack of data / resource) 10 Condition objects (cont.) use a condition object to manage threads that have acquired a lock but cannot proceed with useful work Condition cond = lock.newcondition ();.. lock.lock (); while (!(ok to proceed)) // try until succeeds cond.await (); // data available: do something useful finally { lock.unlock (); must itself check that the condition is (still) valid 11 Condition objects (cont.) some other thread must call the signalall method to wake up any waiting threads change some item used in condition test.. cond.signalall (); // or rarely: signal () the condition wait must always be done in a loop while (! condition) cond.await (); multiple threads may compete to acquire the lock the first one can use up resources, and so others must then enter back to the blocked state to wait additionally, a "spurious wakeup" (without signal) is permitted to occur (depending on the OS) 12 3

Keyword "synchronized" since version 1.0, every object has an implicit lock to be used in so-called monitor methods: public synchronized void method () { body this is the equivalent of the following pseudocode: public void method () { // use explicit lock this.implicitlock.lock (); // pseudocode body finally { this.implicitlock.unlock(); Keyword synchronized (cont.) the monitor lock also has a single implicit associated condition with the following operations wait adds a thread to its set of waiting threads notifyall unblocks all waiting threads to compete for access these correspond to the following lock calls implicitcondition.await (); // pseudocode implicitcondition.signalall (); the wait and notifyall methods are final methods in Object so the Condition methods had to be renamed differently: await and signalall 13 14 Synchronized code blocks an implicit lock can be acquired also by entering a code block synchronized by an object lock: synchronized (obj) { critical section // any object // implicit lock and unlock the lock is reentrant: if a thread has acquired the lock, it can acquire it again (increments a count) similarly, a monitor method can call other monitor methods with the same implicit lock without waiting you can declare a static monitor method: it uses the the associated class object ("X.class") as its lock Limitations of implicit locks and conditions you cannot interrupt a thread that is waiting to acquire a lock you cannot specify a timeout when trying to acquire a lock having only one single condition per lock can be inefficient cannot separate buffer empty (cannot take) vs. buffer full (cannot put) conditions the virtual machine locking primitives do not map well to the most efficient locking mechanisms available in modern hardware 15 16 4

Lock testing and timeouts can be cautious about acquiring a lock: if (mylock.trylock ()) { // now the thread owns the lock do something finally { mylock.unlock (); else { do something else can call trylock with a timeout parameter: if (mylock.trylock(10,timeunit.milliseconds))... TimeUnit can be: SECONDS, MILLISECONDS, MICROSECONDS, or NANOSECONDS. 17 Lock testing and timeouts (cont.) if you call trylock with a timeout, then it can throw InterruptedException when interrupted can try to break up deadlocks and such the lockinterruptibly method has the same meaning as trylock with an infinite timeout can also supply a timeout for a condition wait; mycondition.await (10, TimeUnit.MILLISECONDS)); returns if another thread has called signalall - or if the given timeout has elapsed await methods throw an InterruptedException if the thread is interrupted (but awaituninterruptibly) 18 Summary of synchronization operations synchronized (lock) {.. use shared data synchronized void method () {.. use shared data lock.lock () {.. finally { lock.unlock (); // explicit waiting for a condition to proceed:.. while (!(cannot proceed)) wait ();.. // means: this.wait (); catch (InterruptedException e) {.. either anyobject.wait (); or condition.await (); either anyobject.notifyall (); or condition.signalall (); 19 Recommendations 1. it is best to use neither lock/condition nor the old monitor methods/code blocks ("synchronized") in many situations, better to use mechanisms of the java.util.concurrent package that do all the locking and synchronization for you for example, a blocking queue can synchronize threads that work on a common pipeline 2. if the monitor methods work for your situation, prefer using them: less code to write and so less room for error 3. use explicit locks/conditions only if you need the additional power of these constructs 20 5

java.util.concurrent: thread management tools ReentrantReadWriteLock provides shared access for readers, and exclusive access for a writer BlockingQueue <E> can cause a thread to block when trying to add to a full queue or trying to remove from empty one ConcurrentLinkedQueue <E> and ArrayBlockingQueue <E> provide optionally-bounded/bounded thread-safe queues interface ConcurrentMap <K,V> implemented efficiently by ConcurrentHashMap and ConcurrentSkipListMap CopyOnWriteArrayList <E> and CopyOnWriteArraySet <E> provide thread-safe collections (reads outnumber mutations) Callable <T> plus Future <T> can return and hold the result of an asynchronous computation (can test, time-out, and cancel) you can give a Runnable to a thread pool, and one of its idle threads executes it; afterwards, that thread can serve again synchronizers: CyclicBarrier, CountDownLatch, Exchanger, SynchronousQueue, and Semaphore AtomicInteger, AtomicLong, AtomicReference, etc.: lock-free Atomic variables support lock-free thread-safe programming on single variables (objects) extends the notion of volatile: provide atomic and synchronized access to single values (visibility!) enable implementations to use efficient atomic machine instructions that available on processors (but no guarantees: might entail internal locking..) AtomicLong seqno = new AtomicLong (0);.. long next () { return seqno.getandadd(1); // atomic may not work when state involves invariants.. atomic variables do not replace Integer, Long, etc. do not provide hashcode or compareto (since expected to change, no good as Map keys) thread-safe programming on single variables 21 22 A producer-consumer solution class IntProducer implements Runnable { private BlockingQueue <Integer> queue; public IntProducer (BlockingQueue <Integer> q) { queue = q; new Thread (this).start (); public void run () { // "put" may block for (int x = 0; x < 100; x++) { Thread.sleep (delay);.. queue.put (x); catch (InterruptedException e) { A producer-consumer solution (cont.) class IntConsumer implements Runnable { private BlockingQueue <Integer> queue; public IntConsumer (BlockingQueue <Integer> q) { queue = q; new Thread (this).start (); public void run () { // "take" may block while (true) { int value = queue.take ();.. catch (InterruptedException ex) {.. BlockingQueue <Integer> q = new ArrayBlockingQueue <Integer> (10); // capacity 23 24 6