Concurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
|
|
- Steven Jenkins
- 6 years ago
- Views:
Transcription
1 Concurrency in Object Oriented Programs 4 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
2 Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism 2
3 Thread States A thread can be in one of the following states: NEW A thread that has not yet started is in this state. RUNNABLE A thread executing in the Java virtual machine is in this state. BLOCKED A thread that is blocked waiting for a monitor lock is in this state. WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state. TIMED_WAITING A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. TERMINATED A thread that has exited is in this state. 3
4 Thread Control Manage the schedules of multiple threads Hand information from one thread to another Signal one thread that another thread has finished doing something Methods for inter-thread control and synchronisation are: getpriority, setpriority, join, interrupt yield, sleep (for current thread) wait, notify, notifyall (per object) 4
5 Thread Priorities Runnable threads are scheduled for execution by JVM Priority mechanism is platform dependent Depends on VM (and OS) Programmers can get and set priority for individual objects getpriority() setpriority() The scheduler uses priorities to allocate CPU time ADVICE: Avoid use of priorities May cause liveness problems e.g. via priority inversion Introduces platform dependence Too weak to protect critical sections! Usually sufficient to rely on default priority 5
6 Thread.sleep Put target thread to sleep for a specified time VM guarantees a minimum sleep time Does not give up locks Any held continue to be held while sleeping Should usually release locks before sleep sleep is useful for providing timeouts controlling the speed of applications e.g. specifying framerates for multimedia presentations sleep responds to an interrupt on the thread by exiting, clearing interrupt status and throwing an InterruptedException 6
7 Sleep Example public class Sleep { public static void main(string args[]) throws InterruptedException { final int N = 10; for (int i = N; i > 0; --i) { // Pause for 10, 9,... 1 seconds Thread.sleep(1000 * i); // Awake indicator System.out.print("."); System.out.println(); 7
8 Thread.yield() Causes current thread to pause Gives up the CPU Allows other threads to execute But no guarantee about which order others may run Current thread may just start up again Similar to Thread.sleep(0) Except for throwing of InterruptedExceptions 8
9 object.wait() A method of the Object class Cause current thread to wait Current thread must hold the target object s lock when called release the lock and place thread on wait queue for the lock Resumption occurs if one of following occurs Waiting thread is interrupted resumes, clears interrupt status, and throws InterruptedException Another thread invokes the notify()/notifyall() methods for the target object 9
10 object.notify() or notifyall() Which of these should be called? Unless there is only one condition for an object that may be waited on call notifyall() and re-check the condition for that thread while(!condition) wait(); with try catch InterruptedException handling Only use notify() when you are sure that any thread that might be waiting can make use of the condition causing the notification 10
11 thread.interrupt() Send an indication to a thread that it should stop and do something else useful for external signals Programmers determine exactly how a thread responds to an interrupt Interrupt handling: If thread is currently blocked by wait, sleep or join interrupt status is cleared, InterruptedException is thrown, and thread is resumed otherwise interrupt status of thread is set 11
12 Programming with Interrupts Handle InterruptedException in blocking methods for (int i = 0; i < importantinfo.length; i++) { //Pause for 4 seconds try { Thread.sleep(4000); catch (InterruptedException e) { //We've been interrupted: no more messages. return; System.out.println(importantInfo[i]); 12
13 Interrupt Status Thread.interrupted() tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. So normally programmer must code some interrupt handling whenever this returns true thread.isinterrupted() tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method. 13
14 Thread.interrupted() Programmers can explicitly check the interrupt status of thread when no call throws InterruptedException useful for long running methods for (int i = 0; i < inputs.length; i++) { heavycrunch(inputs[i]); if (Thread.interrupted()) { //We've been interrupted: no more crunching. return; 14
15 thread.join() Force the current thread to wait until another thread terminates used to define synchronization points This thread may continue after another thread has done its business It can provide an alternative to use of locks when different threads are strongly interdependent join responds to an interrupt on the thread by exiting, clearing interrupt status and throwing an InterruptedException 15
16 Example of Thread Join Runnable r1 = ; Runnable r2 = ; Thread t1 = new Thread (r1); Thread t2 = new Thread (r2); t1.start(); t2.start(); // other computation. Do not use r1 or r2 t1.join(); // block until t1 is done t2.join(); // block until t2 is done //Now use r1 and r2 holding results of t1 and t2 computations 16
17 Terminating Threads Normal termination run() terminates Abnormal termination Exception that propagates beyond run() method causes thread termination can define uncaught exception handler for individual threads, or accept default System termination Runtime.exit() 17
18 Comments on Thread Control In general, it is advisable not to directly control thread execution Better approach is to rely on a higher level pattern of thread use The Java Concurrency Framework provides a better option Use executors to separate submission of runnable tasks from execution policy 18
19 Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism 19
20 Organise Task Execution Each task represents a small fraction of the application's processing capacity We should identify sensible task boundaries ideally, tasks should be as independent as possible independence facilitates concurrency Most server applications offer a natural choice of task boundary individual requests as task boundaries usually requests offer both independence and appropriate task sizing 20
21 Executing Tasks Sequentially The simplest way to organise tasks is to execute tasks sequentially in a single thread class SingleThreadWebServer { public static void main(string[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { Socket connection = socket.accept(); handlerequest(connection); 21
22 Creating Threads for Tasks A more responsive approach is to create a new thread for servicing each request class ThreadPerTaskWebServer { public static void main(string[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handlerequest(connection); ; new Thread(task).start(); 22
23 Consequences of Executing Tasks in Threads Task processing is offloaded from the main thread this enables the main loop to resume waiting for the next incoming connection more quickly Tasks can be processed in parallel this enables multiple requests to be serviced simultaneously Task-handling code must be thread-safe 23
24 Disadvantages of Unbounded Thread Creation Thread life cycle overhead thread creation and teardown are not free Resource consumption active threads consume system resources, especially memory Stability there is a limit on how many threads can be created We need to place some bound on how many threads the application creates 24
25 The Executor Framework We have seen two policies for executing tasks execute tasks sequentially in a single thread execute each task in its own thread Both have serious limitations either poor responsiveness and throughput or poor resource management The third option for thread management use bounded queues to prevent an application from overloading The primary abstraction for task execution in the Java libraries is not Thread, but Executor Since Java 5 25
26 The Executor Interface java.util.concurrent provides a flexible thread pool implementation as part of the Executor framework public interface Executor { void execute(runnable task); Decouple task submission from task execution tasks are represented by Runnable objects Support a wide variety of task execution policies 26
27 Web Server Using Executor class TaskExecutionWebServer { private static final int NTHREADS = 100; private static final Executor exec = Executors.newFixedThreadPool(NTHREADS); public static void main(string[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handlerequest(connection); ; exec.execute(task); 27
28 Implement the Executor Interface Executor interface can be implemented to support different task execution policies public class ThreadPerTaskExecutor implements Executor { public void execute(runnable r) { new Thread(r).start(); public class WithinThreadExecutor implements Executor { public void execute(runnable r) { r.run(); 28
29 Execution Policies An execution policy specifies what, where, when, and how of task execution in what thread will tasks be executed? in what order should tasks be executed? FIFO, LIFO, priority order how many tasks may execute concurrently? how many tasks may be queued pending execution? if a task has to be rejected because the system is overloaded, which task should be selected as the victim, and how should the application be notified? what actions should be taken before or after executing a task? 29
30 Execution Policies Execution policies must deal with resource management issues the optimal policy depends on the available computing resources and your quality-of-service requirements Decoupling task submission from execution has benefits we can easily specify the execution policy and subsequently change it without great difficulty it becomes practical to select an execution policy at deployment time matching to available system resources e.g. number of CPUs 30
31 Threads Pools A thread pool manages a homogeneous pool of worker threads bound to a queue holding tasks waiting to be executed The lifecycle of a worker thread request the next task from the queue execute the task wait for another task 31
32 Creating Thread Pools java.util.concurrent.executors provides static factory methods for creating thread pools see Java API docs newfixedthreadpool return a thread pool with constant size newcachedthreadpool return a thread pool without bound size, but always try to reuse existing threads first newsinglethreadexecutor newscheduledthreadpool 32
33 Advantages of Thread Pools Reuse an existing thread instead of creating a new one reduce overhead of thread creation/teardown Improve responsiveness immediately execute a task without latency associated with thread creation Exploit multiple processors without exhausting resources enough threads to keep processors busy not too many threads to exhaust resources 33
34 ExecutorService Interface ExecutorService interface extends Executor, with methods for lifecycle management: public interface ExecutorService extends Executor { void shutdown(); List<Runnable> shutdownnow(); boolean isshutdown(); boolean isterminated(); boolean awaittermination(long timeout, TimeUnit unit) throws InterruptedException; //... additional convenience methods for task submission 34
35 Web Server with Shutdown class LifecycleWebServer { private final ExecutorService exec =...; public void start() throws IOException { ServerSocket socket = new ServerSocket(80); while (!exec.isshutdown()) { try { Socket conn = socket.accept(); exec.execute(new Runnable() { public void run() { handlerequest(conn); ); catch (RejectedExecutionException e) { if (!exec.isshutdown()) log("task submission rejected", e); 35
36 Web Server with Shutdown public void stop() { exec.shutdown(); void handlerequest(socket connection) { Request req = readrequest(connection); if (isshutdownrequest(req)) stop(); else dispatchrequest(req); 36
37 Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism 37
38 Case Study: Page Renderer The page-rendering portion of a browser application takes a page of HTML and renders it into an image buffer We will develop several versions that admit different degrees of concurrency Examples are from Java Concurrency in Practice The simplest approach is to process the HTML document sequentially as text markup is encountered, render it into the image buffer as image references are encountered, fetch the image over the network and draw it into the image 38
39 Sequential Page Renderer public class SingleThreadRenderer { void renderpage(charsequence source) { rendertext(source); List<ImageData> imagedata = new ArrayList<ImageData>(); for (ImageInfo imageinfo : scanforimageinfo(source)) imagedata.add(imageinfo.downloadimage()); for (ImageData data : imagedata) renderimage(data); 39
40 Runnable vs Callable Both Runnables and Callables are tasks that can be processed by an Executor Runnable cannot return a value or throw checked exceptions it can only have side effects Callable can return a value and throw an exception public interface Callable<V> { V call() throws Exception 40
41 Callable and Future The lifecycle of a task executed by an Executor has four phases: created, submitted, started, and completed once a task is completed, it stays in that state forever Future represents the lifecycle of a task provide methods to test whether the task has completed or been cancelled, retrieve its result, and cancel the task 41
42 The Future Interface public interface Future<V> { boolean cancel(boolean mayinterruptifrunning); boolean iscancelled(); boolean isdone(); V get() throws InterruptedException, ExecutionException, CancellationException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, CancellationException, TimeoutException; 42
43 ExecutorService Interface (ctd.) public interface ExecutorService extends Executor { // lifecycle management methods // additional convenience methods for task submission <T> Future<T> submit(callable<t> task); <T> Future<T> submit(runnable task, T result); Future<?> submit(runnable task); <T> List<Future<T>> invokeall(collection<? extends Callable<T>> tasks) <T> List<Future<T>> invokeall(collection<? extends Callable<T>> tasks) long timeout, TimeUnit unit) throws InterruptedException; <T> T invokeany(collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException; <T> T invokeany(collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; 43
44 Page Renderer with Future Divide page render into two tasks to make it more concurrent one renders the text (largely CPU-bound) one downloads all the images (largely I/O-bound) Callable and Future can help us express the interaction between these cooperating tasks create a Callable to download all the images a future is returned to describe the Callable execution when we need the images, we call Future.get() to wait for the result 44
45 Page Renderer with Future public class FutureRenderer { private final ExecutorService executor =...; void renderpage(charsequence source) { final List<ImageInfo> imageinfos = scanforimageinfo(source); Callable<List<ImageData>> task = new Callable<List<ImageData>>() { public List<ImageData> call() { List<ImageData> result = new ArrayList<ImageData>(); for (ImageInfo imageinfo : imageinfos) result.add(imageinfo.downloadimage()); return result; ; 45
46 Page Renderer with Future Future<List<ImageData>> future = executor.submit(task); rendertext(source); try { List<ImageData> imagedata = future.get(); for (ImageData data : imagedata) renderimage(data); catch (InterruptedException e) { // We don't need the result, so cancel the task too future.cancel(true); catch (ExecutionException e) { throw launderthrowable(e.getcause()); 46
47 Render Page Elements as They Become Available public class Renderer { private final ExecutorService executor; Renderer(ExecutorService executor) { this.executor = executor; void renderpage(charsequence source) { final List<ImageInfo> info = scanforimageinfo(source); CompletionService<ImageData> completionservice = new ExecutorCompletionService<ImageData>(executor); for (final ImageInfo imageinfo : info) completionservice.submit(new Callable<ImageData>() { ); public ImageData call() { return imageinfo.downloadimage(); 47
48 Render Page Elements as They Become Available rendertext(source); try { for (int t = 0, n = info.size(); t < n; t++) { Future<ImageData> f = completionservice.take(); ImageData imagedata = f.get(); renderimage(imagedata); catch (InterruptedException e) { Thread.currentThread().interrupt(); catch (ExecutionException e) { throw launderthrowable(e.getcause()); 48
Parallel Programming Practice
Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class
More information[module lab 1.2] STRUCTURING PROGRAMS IN TASKS
v1.0 Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.2] STRUCTURING PROGRAMS IN TASKS 1 STRUCTURING CONCURRENT PROGRAMS INTO TASKS Task concept abstract,
More informationParallel Programming Practice
Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class
More informationProgrammazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci
v1.0 20130510 Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci [module lab 3.1] TASK FRAMEWORKS 1 STRUCTURING CONCURRENT PROGRAMS INTO
More informationFinal Concurrency. Oleg October 27, 2014
Final Concurrency Oleg Šelajev @shelajev oleg@zeroturnaround.com October 27, 2014 Feedbacks Task Executors Fork-Join framework Completable Future Agenda 2 HOMEWORK 4 FEEDBACK THREAD LOCAL VARIABLES TASK
More informationSUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS
SUMMARY CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS Callable tasks Futures Executors Executor services Deadlocks PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento
More information[module lab 1.3] CANCELLATION AND SHUTDOWN
v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.3] CANCELLATION AND SHUTDOWN 1 STOPPING THREADS AND TASKS An activity is cancellable if external
More informationConcurrency Utilities: JSR-166
Concurrency Concurrency Utilities: JSR-166 Enables development of simple yet powerful multi-threaded applications > Like Collection provides rich data structure handling capability Beat C performance in
More informationThe Java ExecutorService (Part 1)
The Java ExecutorService (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning
More informationCharlie Garrod Bogdan Vasilescu
Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 4: Concurrency Introduc9on to concurrency, part 4 Design paderns and frameworks for concurrency Charlie Garrod Bogdan Vasilescu
More informationOutline. Command Pattern. Examples. Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram
Outline Command Pattern Goal & Applications Motivation (undo / redo) Structure & participants Sequence diagram Examples javax.swing.action java.util.timer java.util.concurrent.executorservice Callable
More informationCONCURRENT API AND PARALLEL PROGRAMMING
MODULE 11 CONCURRENT API AND PARALLEL PROGRAMMING Module 11.A THREAD MODEL: RUNNABLE, CALLABLE, FUTURE, FUTURETASK Threads > What are threads? Threads are a virtual CPU. > The three parts of at thread
More informationCS 159: Parallel Processing
Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level
More informationLecture 03: Thread API (continue)
Lecture 03: Thread API (continue) SSC2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Lecture 03 1 Recap Extending Thread or implementing Runnable Thread terminology Stopping Threads
More informationThread Pools SE 441. Prof. Bullinger
Thread Pools SE 441 Prof. Bullinger Thread Pools Thread Pool Limitations Sizing Thread Pools ThreadPoolExecutor Queuing Tasks Parallelizing Loops Thread Pool Limitations Task Dependencies Different types
More informationChair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization
More informationThreads Chate Patanothai
Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?
More informationUNIT V CONCURRENT PROGRAMMING
UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such
More informationCMSC 132: Object-Oriented Programming II. Threads in Java
CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files
More informationSUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams
SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi
More informationCST242 Concurrency Page 1
CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization
COMP 213 Advanced Object-oriented Programming Lecture 23 Shared Variables and Synchronization Communicating Threads In the previous lecture, we saw an example of a multi-threaded program where three threads
More informationCharlie Garrod Michael Hilton
Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 5: Concurrency Introduc9on to concurrency, part 4 Concurrency frameworks Charlie Garrod Michael Hilton School of Computer Science
More informationMultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course
Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class
More informationAdvanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City
Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class
More informationJava Threads. Written by John Bell for CS 342, Spring 2018
Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.
More information7. MULTITHREDED PROGRAMMING
7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread
More informationComputation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007
CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes
More informationCONCURRENCY IN JAVA Course Parallel Computing
CONCURRENCY IN JAVA Course Parallel Computing Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Java on a NUMA Architecture Loading
More informationMulti-threading in Java. Jeff HUANG
Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading
More informationChapter 32 Multithreading and Parallel Programming
Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to
More informationNote: Each loop has 5 iterations in the ThreeLoopTest program.
Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called
More informationJava Threads. COMP 585 Noteset #2 1
Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the
More informationOnly one thread can own a specific monitor
Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification
More informationThreads Questions Important Questions
Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions
More informationJSR 236 Status Jan 28, 2013
JSR 236 Status Jan 28, 2013 Anthony Lai Agenda Introduction Overview Current Status 2 Introduction Provides asynchronous capabilities to Java EE application components, using extension
More informationJava Threads. Introduction to Java Threads
Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent
More informationMultithreaded Programming
Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes
More informationBasics of. Multithreading in Java
Basics of programming 3 Multithreading in Java Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction
More informationCOMP31212: Concurrency A Review of Java Concurrency. Giles Reger
COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other
More informationCS 351 Design of Large Programs Threads and Concurrency
CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level
More informationCMSC 433 Programming Language Technologies and Paradigms. Concurrency
CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.
More informationMultithreading and Interactive Programs
Multithreading and Interactive Programs CS160: User Interfaces John Canny. This time Multithreading for interactivity need and risks Some design patterns for multithreaded programs Debugging multithreaded
More informationAnimation Part 2: MoveableShape interface & Multithreading
Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply
More informationSimpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0
Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0 Brian Goetz Principal Consultant, Quiotix Corp David Holmes Staff Engineer, Sun Microsystems, Inc. TS-4915 2006 JavaOne SM Conference
More informationAdvanced Programming Methods. Lecture 6 - Concurrency in Java (1)
Advanced Programming Methods Lecture 6 - Concurrency in Java (1) Overview Introduction Java threads Java.util.concurrent References NOTE: The slides are based on the following free tutorials. You may want
More informationJAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling
JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;
More informationUnit - IV Multi-Threading
Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first
More informationOverview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1
CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms
More informationMultithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science
Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the
More informationCOMP 322: Fundamentals of Parallel Programming
COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 28: Java Threads (contd), synchronized statement Vivek Sarkar Department of Computer Science
More informationPrinciples of Software Construction: Objects, Design, and Concurrency. Concurrency: More Design Tradeoffs School of Computer Science
Principles of Software Construction: Objects, Design, and Concurrency Concurrency: More Design Tradeoffs Christian Kästner Bogdan Vasilescu School of Computer Science 1 2 So far on concurrency Primitives
More informationCS11 Java. Fall Lecture 7
CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)
More informationObject Oriented Programming. Week 10 Part 1 Threads
Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent
More informationMultitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking
Java Thread Multitasking Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking Allows programs (processes) to run concurrently
More information-Aditya Bhave CSCI-5448 Graduate Presentation
-Aditya Bhave CSCI-5448 Graduate Presentation 04-01-2011 MSEE at CU finishing up in Summer 11 Work full time at Alticast Inc Background in Embedded Systems Media Processing Middleware Cable TV industry
More informationMultithreading using Java. Dr. Ferdin Joe John Joseph
Multithreading using Java Dr. Ferdin Joe John Joseph 1 Agenda Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing Shared Resources Synchronisation Assignment
More informationConcurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University
Concurrent Programming Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University 1 Objectives You will learn/review: What a process is How to fork and wait for processes What a thread is How to spawn
More informationAdvanced Concepts of Programming
Berne University of Applied Sciences E. Benoist / E. Dubuis January 2005 1 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate
More informationIntroduction to Java Threads
Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The
More informationConcurrent Programming using Threads
Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object
More informationCS193k, Stanford Handout #8. Threads 3
CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current
More informationModule - 4 Multi-Threaded Programming
Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is
More informationUnit 4. Thread class & Runnable Interface. Inter Thread Communication
Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more
More informationG52CON: Concepts of Concurrency
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Java implementations of concurrency process and threads
More informationWhat is a thread anyway?
Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently
More informationCS 556 Distributed Systems
CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that
More informationMultithreading. Introduction and Basics. Classical Model. New Model. Summary. Multithreading Basics Problems with Multithreading
Multithreading Introduction and Basics Multithreading Basics Problems with Multithreading Classical Model Synchronization Threads und Swing New Model Executors and Futures Synchronization Concurrent Collections
More informationCSCI 201L Written Exam #1 Fall % of course grade
Final Score /15 Name SOLUTION ID Extra Credit /0.5 Lecture Section (circle one): TTh 8:00-9:20 TTh 9:30-10:50 TTh 11:00-12:20 CSCI 201L Written Exam #1 Fall 2017 15% of course grade The exam is one hour
More informationProgramming in Java
320341 Programming in Java Fall Semester 2014 Lecture 11: Introduction to Concurrency Instructor: Slides: Jürgen Schönwälder Bendick Mahleko Introduction Multithreaded Programs - A program represents separate,
More informationChapter 8 Applying Thread Pools. Magnus Andersson
Chapter 8 Applying Thread Pools Magnus Andersson Execution policies Not all task are suitable for all execution policies Dependent task Task exploiting thread confinement Response time sensitive tasks
More informationThreads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II
Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running
More informationPrinciples of Software Construction: Concurrency, Part 2
Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5a due now Homework 5 framework goals: Functionally correct Well documented
More information[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY
v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 2.2] GUI FRAMEWORKS & CONCURRENCY 1 GUI FRAMEWORKS & CONCURRENCY Once upon a time GUI applications
More informationNetwork Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)
Network Programming COSC 1176/1179 Lecture 6 Concurrent Programming (2) Threads Recall from last week Every line of Java code is part of a thread There can be one or more threads running in parallel Each
More informationOverview of Java Threads (Part 2)
Overview of Java Threads (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning
More informationInfo 408 Distributed Applications Programming Exercise sheet nb. 4
Lebanese University Info 408 Faculty of Science 2017-2018 Section I 1 Custom Connections Info 408 Distributed Applications Programming Exercise sheet nb. 4 When accessing a server represented by an RMI
More informationProduced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar
Design Patterns MSc in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie)! Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie
More informationPrinciples of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, part 4 Can't live with it. Can't live without it.
Principles of Software Construction: Objects, Design and Concurrency 15-214 toad The Perils of Concurrency, part 4 Can't live with it. Can't live without it. Fall 2012 Jonathan Aldrich Charlie Garrod School
More informationThe Java FutureTask. Douglas C. Schmidt
The Java FutureTask Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning Objectives
More informationCMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems
: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either
More informationPrinciples of Software Construction: Objects, Design, and Concurrency. The Perils of Concurrency, Part 3 Can't live with it. Can't live without it.
Principles of Software Construction: Objects, Design, and Concurrency The Perils of Concurrency, Part 3 Can't live with it. Can't live without it. Fall 2014 Charlie Garrod Jonathan Aldrich School of Computer
More informationContents. 6-1 Copyright (c) N. Afshartous
Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004
More informationAdvanced Programming Concurrency
Advanced Programming Concurrency Concurrent Programming Until now, a program was a sequence of operations, executing one after another. In a concurrent program, several sequences of operations may execute
More informationThreads & Timers. CSE260, Computer Science B: Honors Stony Brook University
Threads & Timers CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Multi-tasking When you re working, how many different applications do you have open at one
More informationJava s Implementation of Concurrency, and how to use it in our applications.
Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video
More informationG Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University
G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12
More informationCOURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE
COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread
More informationChapter 4: Threads. Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads
Chapter 4: Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads Chapter 4: Threads Objectives To introduce the notion of a
More informationUnit III Rupali Sherekar 2017
Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception
More informationBuch gefunden? Im Blackboard eingetragen? Abgabe 1. Übung: , 23:59
Buch gefunden? Im Blackboard eingetragen? Abgabe 1. Übung: 09.04., 23:59 1 www.msproteomics.org Ver teil tes Rechnen und Parallelprogrammierung: Introduction to Multi-Threading in Java Based on the book
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and
More informationThe Dining Philosophers Problem CMSC 330: Organization of Programming Languages
The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on
More informationConcurrent Computing CSCI 201 Principles of Software Development
Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking
More informationOverview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions
CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to
More informationCMSC 330: Organization of Programming Languages. The Dining Philosophers Problem
CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks
More informationMultitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit
Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking
More informationParadigmas de Computação Paralela
Paradigmas de Computação Paralela Concurrent/Parallel Programming in OO /Java João Luís Ferreira Sobral jls@... Specification of concurrency/parallelism Benefits from concurrent programming Programs that
More informationThreads and Parallelism in Java
Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program
More information