Java Thread and Memory Model

Slides:



Advertisements
Similar presentations
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Advertisements

1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Threads, SMP, and Microkernels Chapter 4. Process Resource ownership - process is allocated a virtual address space to hold the process image Scheduling/execution-
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Computer Systems/Operating Systems - Class 8
Multithreading The objectives of this chapter are:
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
1 Chapter 4 Threads Threads: Resource ownership and execution.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
A. Frank - P. Weisberg Operating Systems Introduction to Tasks/Threads.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Chapter 51 Threads Chapter 5. 2 Process Characteristics  Concept of Process has two facets.  A Process is: A Unit of resource ownership:  a virtual.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Chapter 4: Threads. 4.2CSCI 380 Operating Systems Chapter 4: Threads Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
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.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
1 Web Based Programming Section 8 James King 12 August 2003.
Internet Software Development Controlling Threads Paul J Krause.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
1 Lecture 4: Threads Advanced Operating System Fall 2010.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
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.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th edition, Jan 23, 2005 Chapter 4: Threads Overview Multithreading.
Module 2.0: Threads.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
CMSC 330: Organization of Programming Languages Threads.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
1 Threads, SMP, and Microkernels Chapter 4. 2 Process Resource ownership - process includes a virtual address space to hold the process image Scheduling/execution-
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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.
Big Picture Lab 4 Operating Systems C Andras Moritz
Java Thread Programming
Multithreading The objectives of this chapter are:
Multithreading / Concurrency
Multithreading.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Multithreading Chapter 23.
Multithreading.
Multithreading.
Multithreaded Programming
Threads Chapter 4.
Multithreading in java.
Threads and Multithreading
Foundations and Definitions
Multithreading The objectives of this chapter are:
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Thread and Memory Model By Xijun Zhang #104549

Question Can this result in i = 0 and j = 0?

Contents Thread review Threads in Java Programmer’s view of Java memory model

Threads Has an execution state (running, ready, etc.) Saves thread context when not running Has an execution stack and some per-thread static storage for local variables Has access to the memory address space and resources of its process all threads of a process share this when one thread alters a (non-private) memory item, all other threads (of the process) sees that a file open with one thread, is available to others

Single Threaded and Multithreaded Process Models Thread Control Block contains a register image, thread priority and thread state information

Benefits of Threads vs Processes Takes less time to create a new thread than a process Less time to terminate a thread than a process Less time to switch between two threads within the same process

Benefits of Threads Since threads within the same process share memory and files, they can communicate with each other without invoking the kernel Therefore necessary to synchronize the activities of various threads so that they do not obtain inconsistent views of the data

Java Thread Support Reside in Three Places The java.lang.Thread class The java.lang.Object class The Java language and virtual machine

Two ways to create threads Extending the java.lang.Thread class Implementing the java.lang.Runnable interface

Extending the Thread class Can build a thread by extending java.lang.Thread class You must supply a public void run() method Start a thread by invoking the start() method When a thread starts, it executes run() method When run() finished, the thread is finished/dead

Interface Runnable Extending Thread means can’t extend anything else Instead implement Runnable (Declares an object has a void run() method) Creating a new thread by giving is an object of type Runnable Constructors: Thread(Runnable target) Thread(Runnable target, String name)

Thread States Running: The state that all threads aspire to Various waiting states: Waiting, Sleeping, Suspended, Blocked Ready: Not waiting for anything except the CPU Dead: All done

Two approaches to implement Thread schedulers Preemptive scheduling (e.g. Solaris) Time-sliced or round-robin scheduling e.g. Macintosh, Windows Java Thread is platform dependent

Synchronization Threads share the same memory space, i.e. they can share resources It is desirable that only one thread at a time has access to a shared resource Java use the key word synchronized for critical section

Monitors At any given time, no more than one thread can own the monitor and thereby have access to the shared resource A monitor thus implements a mutually exclusive locking mechanism All Java objects have a monitor, and each object can be used as a mutually exclusive lock, providing the ability to synchronize access to shared resources

Synchronized Methods A method can be synchronized (add synchronized before the return type) Obtains a lock on object referenced by this before starting method ( releases lock when method completes) A static synchronized method (locks the class object)

Synchronized statement synchronized (obj) {block} Obtains a lock on obj before executing block Releases lock once block completes Provides finer grain of control Allows you to lock arguments to a method

Using wait a.wait() --gives up locks on a --adds thread to wait set for a --suspends thread a.wait(int m) --limits suspension to m milliseconds

Using notify a.notify() resumes one thread from a’s waiting list and remove it from wait set, no control over which thread a.notifyAll() resumes one thread on a’s waiting list resumed task must reacquire lock before continuing

Synchronization Atomicity --locking to obtain mutual exclusion --Atomic read/write granularity Visibility --ensuring that changes in object fields on one object are seen in another thread Ordering --ensuring that you aren’t surprised by the order in which statements are executed

Question Can this result in i=0 and j=0?

Answer: Yes! How can i=0 and j=0?

Working Memory v.s. Main Memory Every thread has a working memory in which it keeps its own working copy of variables that it must use or assign. As the thread executes a program, it operates on these working copies. The main memory contains the master copy of every variable.

Low level actions

How can this happen? Compiler can reorder statement or keep values in registers Processor can reorder them On multiprocessor, values not synchronized in global memory Must use synchronization to enforce visibility and ordering as well as mutual exclusion

Synchronization Action //block until obtain lock synchronized (anObject) { //get main memory value of field1 and field2 int x = anObject.field1; int y = anObject.field2; anObject.field3 = x + y; //commit value of field3 to main memory } // release lock moreCode();

When are actions visible to other thread?

What does volatile mean? C/C++ spec --There is no implementation independent meaning of volatile Situation a little better with Java Technology --volatile reads/writes guaranteed to go directly to main memory e.g. can’t be cached in registers or local memory

Using volatile Volatile used to guarantee visibility of writes --stop() must be declared volatile --Otherwise, compiler could keep in register class Animator implements Runnable { private volatile boolean stop = false; public void stop() { stop = true;} public void run() { while (!stop) oneStep(); } private void oneStep() {/*……*/}

Some problems of current Java Memory Model Some JVMs do not implement volatile correctly There are some corner cases Experts are trying to fix the current JMM