Concurrent Programming in JAVA Steve Pruett - Introduction Jaime Mendez – Thread Creation Adrian Garcia – Thread Management Eric Orozco – Thread Safety.

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

Concurrent Programming Abstraction & Java Threads
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this?
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Concurrency CS 510: Programming Languages David Walker.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 11.
1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Internet Software Development More stuff on Threads Paul Krause.
Java Programming: Advanced Topics
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
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.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
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.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
Internet Software Development Controlling Threads Paul J Krause.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Java Thread and Memory Model
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.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
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.
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.
Java Thread Programming
Multithreading / Concurrency
PROCESS MANAGEMENT IN MACH
Multi Threading.
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
21 Threads.
Computer Science 2 06A-Java Multithreading
Multithreading in java.
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Concurrent Programming in JAVA Steve Pruett - Introduction Jaime Mendez – Thread Creation Adrian Garcia – Thread Management Eric Orozco – Thread Safety and Liveness

Key Terminology Flow of Control - particular sequence of actions that the CPU performs Process - individual program, representing a larger and more complex flow of control handled by the operating system Thread – specific, smaller flow of control within a given process Multitasking - procedure that allows threads or processes to share time on a single processor by taking turns

Introduction Concurrent programming is the creation of more than one flow of control, functioning simultaneously, each with the ability to communicate with other operating flows. This can be implemented in two ways: –With a single program that contains multiple threads which share the same variables and object instances –With multiple programs which run at the same time and can pass messages to each other

Graphical Example of Flow of Control: When operating in sequence, one flow must be completed before another can begin, but more can be accomplished in the same time with concurrently operating flows. SequentialConcurrent Complex Concurrent

Pros & Cons of Concurrent Programming Pros:a. Increased speed b. Reduced idle time c. Better usage of multiprocessor machines Cons:a. Harder to program b. High memory usage due to switching, instantiation, and synchronization c. Race condition

History The idea of simultaneously running processes was originally implemented in the 1960’s with independent input-output device controllers, called channels. These channels acted as small computers, which were individually programmable. Advancements such as semaphores, message passing, multiple CPU’s, and the like have brought concurrent programming up to its current functionality and popularity.

Examples of Concurrent Programming Creating a more responsive application that can readily accept user input even if it is already involved in very intensive computational procedures. It can be applied in a server to give multiple clients simultaneous access to that server. Reactive system - program that continually checks collections of information for any changes, and reacts to those changes appropriately (autopilot systems, patient monitoring systems, etc.)

Creating Threads Two basic approaches –Extending the java.lang.Thread class –Implementing the java.lang.Runnable interface

Creating Threads My Thread Run() RunnableThread

Creating Threads Extending the Thread Class –All threads are instances of the Thread class –Run() method must be overriden in the subclass (Invoked indirectly)

Creating Threads Template for a new Thread class public class MyThread extends Thread{ public void run(){ //the thread body } //other methods and fields }

Creating Threads Extending Thread Example –Simple Infinite Counter

Thread 1 Thread 2

Creating Threads Implementing a Runnable Interface Java only supports a single inheritance among classes ( Ex: applets cannot also extend Thread class at the same time)

Creating Threads Runnable Interface public interface Runnable { public abstract void run(); } Template for a new Thread implementing the Runnable interface public class MyThread extends AnotherClass Implements Runnable { public void run(){ //the thread body } //other methods and fields }

Creating Threads Implementing the Runnable Interface Example –Simple Infinite Counter II

Thread 1 Thread 2

Thread Management Thread Life Cycle –Thread State Changes Thread Manipulation Methods –Thread Class –Object Class Thread Priority & Scheduling

Thread Life Cycle Life Cycle Consists of Three States: –New –Alive –Dead New State –Thread is in this state after its creation (new myThread();). –Remains in New state until start() method is invoked.

Thread Life Cycle Alive State –Thread enters this state when start() method is invoked –State is divided into two sub-states Runnable – Threads in this state are ready to run but may not necessarily be running Blocked – Threads in this state have been blocked and are not ready to run. Must wait until a method call moves thread back to Runnable state.

Thread Life Cycle Dead State –Thread enters this state when run() method has terminated and returned –Once in this state, thread is terminated –Change is final and irreversible Threads cannot jump back to a previous state. Threads are New, then Alive, then Dead.

Thread Life Cycle

Thread Manipulation Methods Thread’s state changes can be manipulated through the use of methods from two classes: –Thread Class –Object Class Methods from Thread Class –start() – Thread should be in New state. Method causes thread to enter Alive state and begin execution.

Thread Manipulation Methods –sleep() – Thread should be in Runnable state. Method causes thread to enter Blocked state for a defined amount of time after which it returns to Runnable state. –join() – Thread should be in Runnable state. Thread is blocked and waits until another thread stops execution before it returns to Runnable state. –yield() – Remains in Runnable state but gives other threads an opportunity to run.

Thread Manipulation Methods –interrupt() – If thread is in Runnable state, interrupted flag will be set. If thread is in Blocked state, it is awakened, enters Runnable state. –isAlive() – Returns true if thread is in Alive state, false otherwise. –isInterrupted() – Returns true if the interrupted flag is set.

Thread Manipulation Methods Object Class –wait() –notify() –notifyAll() These methods are used to change a thread’s state from Runnable to Blocked.

Priority & Scheduling Threads have priority attributes. Highest priority executes first. Priority can be changed by programmer. –setPriority(int newPriority) Possible for more than 1 thread to have the same priority –JVM determines which executes first.

Priority & Scheduling A thread with higher priority will obstruct a thread of lower priority. Program correctness should not depend on Priorities.

Thread Safety Safety Properties Problem –Race Hazard (AKA Race Condition) Solution –Synchronization – Creating Locks

Example of a Race Hazard The following piece of code can print either a 0 or a 1 depending on how the threads are scheduled. public class DataRace { static int a = 0; public static void main() { new MyThread().start(); a = 1; } public static class MyThread extends Thread { public void run() { System.out.println(a); }

Examples of Synchronization Class MyClass{ synchronized public void aMethod(){ } Class MyClass{ public void aMethod(){ synchronized(this){ }

Examples of Synchronization Synchronized(expression){ }

Thread Cooperation using Guarded Suspension What is guarded suspension? –before a method is executed, the guard (precondition) is tested –execution continues only when the guard is true –execution is temporarily suspended until the guard becomes true if previously false

What Do We Use to Implement Guarded Suspension? The wait() Method The notify() Method The notifyAll() Method

The wait() Method wait() – The current thread is temporarily blocked and placed in a wait queue associated with the receiving object. The receiving object’s lock is temporarily released. The thread will resume execution when it is awakened by notify() or notifyAll().

The notify() Method notify() – One of the threads in the wait queue will be awakened and removed from the queue. The awakened thread must re-obtain the lock before it can resume at the point immediately after the invocation of wait().

The notifyAll() Method notifyAll() – This method is the same as notify(), except that every thread in the wait queue associated with the receiving object will be awakened and removed from the queue.

When to use What The wait() method should be invoked when a thread is temporarily unable to continue and to allow other threads to proceed The notify() or notifyAll() method should be invoked to make a thread notify other threads that they may proceed

Liveness What is Liveness? Ensure Liveness by Preventing Liveness Failures –Contention –Dormancy –Deadlock –Premature Termination

Liveness Failures Contention - occurs when a runnable thread never gets a chance to run. Dormancy - occurs when a thread that is blocked never becomes runnable. Deadlock - occurs when two or more threads block each other and none can make progress. Premature Termination - occurs when a thread is terminated before it should be and can result in impeding the progress of other threads.

Conclusion Concurrent programming is the practice of using multiple flows of control to achieve greater functionality and performance from software. It may require great caution when practicing, however it may yield great results.

Works Cited Goetz, Brian. “Don't let the ‘this’ reference escape during construction.” Java Theory and practice: Safe construction techniques. IBM. 11 April Hartley, Stephen J. Concurrent Programming. New York: Oxford University Press, 1998 Java Technology. 10 April Sun Microsystems.. Jia, Xiaoping. Object-Oriented Software Development Using Java. 2 nd ed. Boston: Addison Wesley, Lea, Doug. Concurrent Programming In Java. 2 nd ed. Massachusetts: Addison-Wesley, 2000 Book