Concurrent Programming in JAVA What is it? When/How do I use it? When is my class safe? What should I think about during Design?

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

Concurrency 101 Shared state. Part 1: General Concepts 2.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Multithreading The objectives of this chapter are:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
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.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
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()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Internet Software Development Controlling Threads Paul J Krause.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Java Thread and Memory Model
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Java 3: Odds & Ends Advanced Programming Techniques.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
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.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
© Andy Wellings, 2004 Thread Priorities I  Although priorities can be given to Java threads, they are only used as a guide to the underlying scheduler.
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.
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.
Multithreading The objectives of this chapter are:
CSCD 330 Network Programming
Doing Several Things at Once
Multithreading / Concurrency
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Multithreading The objectives of this chapter are:
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Concurrent Programming in JAVA What is it? When/How do I use it? When is my class safe? What should I think about during Design?

What is it? Blocks of code that execute independently of other code blocks within the same process. Known as a thread of control, or simply a thread Same as a machine that does multi-tasking

From Mr. Bunny's Big Cup o' Java "Java supports a deterministic scheduling algorithm called change the priority and see if it makes any difference."

When do I use it? Heavy computational requirements Waiting on I/O Simulation of independent objects GUI interactions Mobile code Embedded Systems Test Suites

How do I use it? (Part 1) Create a class that extends the class Thread –This will limit the capability of the class –Can be a perfect solution however. Create a class that implements the Runnable Interface –Allows a class to maintain its inheritance structure –May have a class implementing Runnable that can be used by many classes within an application.

Example 1 import java.util.Properties; import java.io.*; public class PropertiesThread extends Thread { private String theFileName; public PropertiesThread(String fileName) { theFileName = fileName; }

Example 1 public void run() { File file = new File(theFileName); try { FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); Properties props = System.getProperties(); props.load(bis); } catch (Exception ex) { //handle exception }

Example 1 public class UseProperty { public UseProperty(String propFileName) { PropertyThread propThread = new PropertyThread(propFileName); propThread.start(); //Do More Stuff } public static void main(String[] args) { UseProperty useProps = new UseProperty(args[0]); }

Example 2 public class CreditCard extends Payment implements Runnable { private String cardNumber; private String exprDate; private CCService service = null; public CreditCard () { Thread t = new Thread(this); t.start(); } public void setValues (String aCardNumber, String anExprDate, float anAmount) { cardNumber = aCardNumber; exprDate = anExprDate; setAmount(anAmount); }

Example 2 public String authorize () { while (service == null) { try { Thread.sleep(500); } catch (InterruptedException interEx) { } return service.authorize(cardNumber, exprDate, amount); }

Example 2 public void run() { while (true) { try { service = //Some Lookup Facility break; } catch (Exception ex) { //Decide what to do }

How do I use it? (Part 1) Thread Class start() - This method will create a new thread of control and the code in the run() method will execute run() - This method will do nothing unless it is overridden in a sub-class or a class that implements the Runnable interface was an argument to the Thread’s constructor.

How do I use it? (Part 1) Thread Class interrupt(), interrupted(), isInterrupted() - These methods allow a thread to be canceled, as well as check the status and/or reset the interrupt status for the Thread. yield() - This method pauses the current Thread to allow others to execute. It is merely a hint to the JVM.

How do I use it? (Part 1) Thread Class stop() - DO NOT USE THIS METHOD! It is unsafe. It will throw a ThreadDeath exception that will cause all the locks to be released, exposing possibly damaged objects to other Threads. The code cannot perform any necessary rollback procedures, etc. suspend() - DITTO! Same with the complementary method resume(), use wait() and notify()

When is my class safe? It is Immutable –The class contains no fields –The class contains only fields that are final It contains locking to protect against invalid states for fields. –Using the synchronized key word on methods or code blocks It is Confined –Guaranteeing that only one thread (or at most one thread at a time has access

Examples public class ImmutableHello { public String sayHello(String name) { return “Hello “+name+”!”; } public class SyncPayment { private float amount; public synchronized float getAmount() { return amount; } public synchronized void setAmount(float anAmount) { amount = anAmount; }

Examples Per of Concurrent Programming in Java, page 94: “Atomicity guarantees ensure that when a non-long/double is used in an expression, you will obtain either its initial value or some value that was written by some thread, but not some jumble of bits resulting from two or more threads both trying to write values at the same time. However, as seen below (not shared here), atomicity alone does not guarantee that you will get the value most recently written by any thread. For this reason, atomicity guarantees per se normally have little impact on concurrent program design.”

Types/Examples Method Confinement Thread Confinement Object Confinement public class MyMethodConfinement { public Sring displayBalance(long acctNum) { Account account = new Account(acctNum); return “The Balance is: “+account.getBalance(); }

Examples public class MyThreadConfinement implements Runnable{ static ThreadLocal databaseConn = new ThreadLocal(); final String connectString; public void dbConnection() { try { connectString = System.getProperty(“DATABASE_STR”); Thread thread = new Thread(this); thread.start(); } catch (Exception ex) { //Handle failure }

Examples public void run() { Connection conn = Database.getConnection(connectStr); databaseConn.set(conn); } public ResultSet executeMyQuery() { Connection aConn = (Connection) databaseConn.get(); //Use conn2 to process a query and return a ResultSet }

Examples public class HostObject() { private final NTSObject ntsObject; public HostObject(String name) { ntsObject = new NTSObject(name); } public synchronized String getName() { return ntsObject.getName(); } public synchronized Address getAddress() { return ntsObject.getAddress(); }

What should I think about during Design? Safety vs. Liveliness - Too many locks can increase overhead as well as affect liveliness Look to make sure that 1 lock isn’t being used to protect more than one piece of functionality. Do not lock around long executing blocks of code Do not synchronize on stateless methods

What should I think about during Design? Things I Can Do Separate Synchronization –isolate critical code, proceed on Split independent functionality into separate classes –Host and Helper classes Reduce Synchronization –decide whether or not a field can ever be set to an illegal value –decide whether or not a field can be stale. –remove the accessor itself

What should I think about during Design? Things I Can Do Split the locks themselves Separate fields that are inter-dependent into a separate class.

How do I use it? (Part 2) Utility Classes No way to back off from an attempt to obtain a lock that is held To give up waiting after an amount of time No way to specify a read vs write type lock. Cannot acquire a lock in one method and release in another Can create denial-of-service problems

How do I use it? (Part 2) Utility Classes Read/Write Locks –an interface that contains readLock() and writeLock() methods with the signature of the Sync interface The Mutex class implements the standard Sync interface –acquire, attempt, release

Doug Lea’s Stuff Home Page: util.concurrent (from Home Page): /classes/EDU/oswego/cs/dl/util/concurrent/intro.html