Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }

Slides:



Advertisements
Similar presentations
Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
50.003: Elements of Software Construction Week 10 Thread Pool.
CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Chris Greenhalgh School of Computer Science
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L20 (Chapter 24) Multithreading.
50.003: Elements of Software Construction Week 5 Basics of Threads.
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 some important concepts Simon Lynch
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
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 GUI programming with threads. 2 Threads and Swing Swing is not generally thread-safe: most methods are not synchronized –correct synchronization is.
1 Web Based Programming Section 8 James King 12 August 2003.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Java Threads 1 1 Threading and Concurrent Programming in Java Queues D.W. Denbo.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Dynamic Architectures (Component Reconfiguration) with Fractal.
Synchronizing threads, thread pools, etc.
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.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Reusing threads.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
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.
CSC Multiprocessor Programming, Spring, 2012 Chapter 7 – Cancellation & Shutdown Dr. Dale E. Parson, week 9-10.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multi-Threading in Java
CSC Multiprocessor Programming, Spring, 2011 Chapter 9 – GUI Applications Dr. Dale E. Parson, week 11.
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.
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.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer.
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.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
…in java DThread Pools x. Thread Pools: Why? Source code updates – copy/paste of run/runnable method for each thread is exhausting There is overhead to.
Java Thread Programming
A brief intro to: Parallelism, Threads, and Concurrency
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Thread Pools (Worker Queues) cs
Practice Session 8 Lockfree LinkedList Blocking queues
CSC Multiprocessor Programming, Spring, 2012
Lecture 28 Concurrent, Responsive GUIs
Threads Chate Patanothai.
Threads II IS
Cancellation.
Threads in Java James Brucker.
Using threads for long running tasks.
Software Engineering and Architecture
some important concepts
More concurrency issues
Threads and concurrency / Safety
Presentation transcript:

Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }

Quick Review  Threads can up performance  Java’s 2 parts for thread safety  Atomicity  Visibility  Java’s Primitives  volatile  synchronized  Library Support  Atomic variables  Concurrent collections  Common synchronizers (BlockingQueue)  Threads can up performance  Java’s 2 parts for thread safety  Atomicity  Visibility  Java’s Primitives  volatile  synchronized  Library Support  Atomic variables  Concurrent collections  Common synchronizers (BlockingQueue)

Outline  Executor Framework  Shutdown and cancellation  Swing and Concurrency  Custom Synchronizers  Executor Framework  Shutdown and cancellation  Swing and Concurrency  Custom Synchronizers

Starting Threads  Executor framework public interface Executor { void execute(Runnable command); }  Executor framework public interface Executor { void execute(Runnable command); }

Executor Example class MyTask implements Runnable { public void run() {…} public static void main(…) { Runnable task1 = new MyTask(); Executor exec = /* */; exec.execute(task1); } class MyTask implements Runnable { public void run() {…} public static void main(…) { Runnable task1 = new MyTask(); Executor exec = /* */; exec.execute(task1); }

1 Thread/ Task class OnePer implements Executor { public void Execute(Runnable r){ new Thread(r).start(); } class OnePer implements Executor { public void Execute(Runnable r){ new Thread(r).start(); }

Single Threaded class Just1 implements Executor { public void Execute(Runnable r){ r.run(); } class Just1 implements Executor { public void Execute(Runnable r){ r.run(); }

Provided Thread Pool Executors  newFixedThreadPool  Bounded size  Replace if thread dies  newCachedThreadPool  Demand driven variable size  newSingleThreadExecutor  Just one thread  Replace if thread dies  newScheduledThreadPool  Delayed and periodic task execution  Good replacement for class Timer  newFixedThreadPool  Bounded size  Replace if thread dies  newCachedThreadPool  Demand driven variable size  newSingleThreadExecutor  Just one thread  Replace if thread dies  newScheduledThreadPool  Delayed and periodic task execution  Good replacement for class Timer

Executor Shut-down  Executor is a serice provider  Executor abstracts thread management  To maintain the abstraction, the service should generally provide methods for shutting down the service  JVM cannot shut down until threads do  Executor is a serice provider  Executor abstracts thread management  To maintain the abstraction, the service should generally provide methods for shutting down the service  JVM cannot shut down until threads do

ExecutorService public interface ExecutorService extends Executor { void shutdown(); List shutdownNow(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; } public interface ExecutorService extends Executor { void shutdown(); List shutdownNow(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; }

ExecutorService Notes  Implies three states:  Running  Shutting down  Terminated  shutdown() runs tasks in queue  shutdownNow() returns unstarted tasks  awaitTermination() blocks until the service is in the terminated state  Implies three states:  Running  Shutting down  Terminated  shutdown() runs tasks in queue  shutdownNow() returns unstarted tasks  awaitTermination() blocks until the service is in the terminated state

ExecutorService implementation  ExecutorService is an interface  How do you implement shut down and cancellation?  ExecutorService is an interface  How do you implement shut down and cancellation?

Cancellation in Java  Cooperative, not mandated  Traditional method: interruption  Cooperative, not mandated  Traditional method: interruption Public class Thread { public void interrupt(); public void isInterrupted(); public static boolean interrupted(); … }

Interruption  Just a request!  Sets a flag that must be explicitly cleared!  Some methods clear the flag & throw InterruptedException  Others ignore it, leaving other code to handle it  Just a request!  Sets a flag that must be explicitly cleared!  Some methods clear the flag & throw InterruptedException  Others ignore it, leaving other code to handle it

IMPORTANT!  Your code should follow protocol when interrupted  If interrupted(),  Throw exception  Reset the flag for other code  If InterruptedException  Pass it along  Reset the flag for other code  Don’t swallow, unless your code is handles the interruption policy  Your code should follow protocol when interrupted  If interrupted(),  Throw exception  Reset the flag for other code  If InterruptedException  Pass it along  Reset the flag for other code  Don’t swallow, unless your code is handles the interruption policy

Restoring Interrupted Status catch(InterruptedException e) { Thread.currentThread().interrupt(); } // checks (AND CLEARS!) current thread if (Thread.interrupted()) { Thread.currentThread().interrupt(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } // checks (AND CLEARS!) current thread if (Thread.interrupted()) { Thread.currentThread().interrupt(); }

Handeling Interruption  Long computations “break” to check interrupted status  If interrupted, stop computation, throw InterruptedException or restore the interrupted status  Long computations “break” to check interrupted status  If interrupted, stop computation, throw InterruptedException or restore the interrupted status

Interrupting Non- Blocking Operations  Socket read/writes do not support interruption!  If you detect interruption, close the socket causing read/write to throw an exception  Locks (via synchronized) can not be interrupted  Explicit locks beyond scope of this lecture  Socket read/writes do not support interruption!  If you detect interruption, close the socket causing read/write to throw an exception  Locks (via synchronized) can not be interrupted  Explicit locks beyond scope of this lecture

Future  Interface representing the lifecycle of a task public interface Future { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException, CancellationException V get() throws InterruptedException, ExecutionException, CancellationException, TimeoutException } public interface Future { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException, CancellationException V get() throws InterruptedException, ExecutionException, CancellationException, TimeoutException }

CompletionService  Combines Executor with BlockingQueue  ExecutorCompletionService  Combines Executor with BlockingQueue  ExecutorCompletionService public interface CompletionService { Future poll(); Future poll(long timeout, TimeUnit unit); Future submit(Callable task); Future submit(Runnable task); Future take(); } public interface CompletionService { Future poll(); Future poll(long timeout, TimeUnit unit); Future submit(Callable task); Future submit(Runnable task); Future take(); }

Futures Again  ExecutorService interface also provides public interface ExecutorService { … Future submit(Callable task); Future submit(Runnable task); Future submit(Runnable task, T result); } public interface ExecutorService { … Future submit(Callable task); Future submit(Runnable task); Future submit(Runnable task, T result); }

GUI’s  Are almost always single threaded  That is, they have a dedicated thread for the GUI, but just 1!  Multithreaded has been tried, but has generally failed  Are almost always single threaded  That is, they have a dedicated thread for the GUI, but just 1!  Multithreaded has been tried, but has generally failed

Event Processing  The Swing apps expect short events that can be processed quickly in sequence  So, long running operations must be executed in another thread  Swing troubles are often related to communication between these threads  The Swing apps expect short events that can be processed quickly in sequence  So, long running operations must be executed in another thread  Swing troubles are often related to communication between these threads

Swing Manipulation  Swing does NOT use synchronization, it uses thread confinement  You should almost NEVER create, modify, or query swing components or data models outside the event-dispatching thread  Swing does NOT use synchronization, it uses thread confinement  You should almost NEVER create, modify, or query swing components or data models outside the event-dispatching thread

(A Few Exceptions)  Some components (see JavaDoc)  SwingUtilities.isEventDispatchThrea d  SwingUtilities.invokeLater  SwingUtilities.invokeAndWait  Methods to enqueue repaint or revalidation  Methods for add/remove listeners  Some components (see JavaDoc)  SwingUtilities.isEventDispatchThrea d  SwingUtilities.invokeLater  SwingUtilities.invokeAndWait  Methods to enqueue repaint or revalidation  Methods for add/remove listeners

Short-running Tasks  Short, GUI-confined operations can be programmed entirely in the EDThread  Trivial Example: button that changes color when clicked  Example: information between model and view  Short, GUI-confined operations can be programmed entirely in the EDThread  Trivial Example: button that changes color when clicked  Example: information between model and view

Long-running Tasks  Proposed Handling:  GuiExecutor  newCachedThreadPool  Proposed Handling:  GuiExecutor  newCachedThreadPool

GuiExecutor  import java.util.*;  import java.util.concurrent.*;  public class GuiExecutor extends AbstractExecutorService {  // Singletons have a private constructor and a public factory  private static final GuiExecutor instance = new GuiExecutor();  private GuiExecutor() {}  public static GuiExecutor instance() { return instance; }  public void execute(Runnable r) {  if (SwingUtilities.isEventDispatchThread())  r.run();  else  SwingUtilities.invokeLater(r);  }  /* shutdown, shutdownNow, and awaitTermination throw  UnsupportedOperationException for now */  public boolean isShutdown() {return false; }  public boolean isTerminated() {return false; }  }  import java.util.*;  import java.util.concurrent.*;  public class GuiExecutor extends AbstractExecutorService {  // Singletons have a private constructor and a public factory  private static final GuiExecutor instance = new GuiExecutor();  private GuiExecutor() {}  public static GuiExecutor instance() { return instance; }  public void execute(Runnable r) {  if (SwingUtilities.isEventDispatchThread())  r.run();  else  SwingUtilities.invokeLater(r);  }  /* shutdown, shutdownNow, and awaitTermination throw  UnsupportedOperationException for now */  public boolean isShutdown() {return false; }  public boolean isTerminated() {return false; }  }

Long Running Tasks: Starting  Fire off tasks to thread pool  When completed, use the GuiExecutor to send a task for updating gui  Simple example: status text  Fire off tasks to thread pool  When completed, use the GuiExecutor to send a task for updating gui  Simple example: status text

Long-running Tasks: Cancellation  Instead of execute(), use submit()  Returns a Future that is cancelable  You still have to make your task interruptable  Instead of execute(), use submit()  Returns a Future that is cancelable  You still have to make your task interruptable

Long-running Tasks: Visual Feedback  The books method:  Create a task subclass with some methods callable from EDthread, & others callable elsewhere  I think this is dangerous. If you’re going to do this, you should  Clearly document the methods  Check if you’re in the Edthread  The books method:  Create a task subclass with some methods callable from EDthread, & others callable elsewhere  I think this is dangerous. If you’re going to do this, you should  Clearly document the methods  Check if you’re in the Edthread

BackgroundTask  Code is confusing, hard to follow  If you want to look at it:  Code is confusing, hard to follow  If you want to look at it:

Simpler Solution  Design LR tasks with “hooks”  The hook can be a special communication class  When checking for cancellation, update the hook  Hook schedules update to GUI  Design LR tasks with “hooks”  The hook can be a special communication class  When checking for cancellation, update the hook  Hook schedules update to GUI

Last Notes  Writing your own synchronizers // BLOCKS-UNTIL: not-full public synchronized void put(V v) throws InterruptedException { while (isFull()) wait(); doPut(v); notifyAll(); } // BLOCKS-UNTIL: not-empty public synchronized V take() throws InterruptedException { while (isEmpty()) wait(); V v = doTake(); notifyAll(); return v; }