L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer.

Slides:



Advertisements
Similar presentations
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Advertisements

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Java 5 Threading CSE301 University of Sunderland Harry Erwin, PhD.
Lecture 17: Animation Yoni Fridman 7/27/01 7/27/01.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Multithreading.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threads some important concepts Simon Lynch
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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 Web Based Programming Section 8 James King 12 August 2003.
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 CSc 335 Object-Oriented Programming and Design Spring 2009.
Concurrent Programming and Threads Threads Blocking a User Interface.
Synchronizing threads, thread pools, etc.
C20: Threads see also: ThreadedBallWorld, DropTest, Tetris source examples Not covered: advanced stuff like notify/notifyAll.
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
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.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
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.
SurfaceView.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Multi-Threading in Java
1 OS Review Processes and Threads Chi Zhang
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
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.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Java Thread Programming
A brief intro to: Parallelism, Threads, and Concurrency
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Multi Threading.
Thread Pools (Worker Queues) cs
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Multithreading Chapter 9.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreaded Programming
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Java Concurrency 17-Jan-19.
21 Threads.
Threads in Java James Brucker.
Java Concurrency.
Java Concurrency.
Java Concurrency 29-May-19.
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
some important concepts
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Threads and concurrency / Safety
Presentation transcript:

L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer

Multi-threading Multi-tasking: do multiple things in parallel: –Edit your game –Surf the web –Listen to mp3s –… –Also inside single App: mp3 player (decompress, play, graphics) but usually only 1 or 2 CPUs with 1 or 2 cores that switches between tasks Multi-threading similar, but inside a single program/process/context  share data directly, same classes/methods/variables

Creating threads: 2 ways Subclassing Class Thread class ExpensiveComputation extends Thread –Must implement run() method –Use start() on a new instance: (new ExpensiveComputation()).start(); Implement interface Runnable: class ExpensiveComputation implements Runnable –Must implement run() method –Start by wrapping inside a Thread instance: Thread thread = new Thread(new ExpensiveComputation ()); thread.start(); Both will stop automatically, once run() finishes

Scheduling Can be pre-emptive or cooperative,  Each Thread should regularly call one of yield() wait() sleep() to give other threads a chance to run as well All event handlers (all listeners) and repaint() execute in the same event-handling thread:  methods like “actionPerformed()” should be fast, for more substantial computations they should: Start a new thread Somehow tell another thread what to do Otherwise screen repainting will suffer!

Synchronization If two (or more) threads access some value simultaneously, and at least one wants to modify the value, things can go wrong: a += 10; Thread1: (a1) read a, (b1) compute a+10, (c1) write a Thread2: (a2) read a, (b2) compute a+10, (c2) write a What is the value of a after the following sequence: a1,b1,a2,b2,c2,c1

Synchronized methods public synchronized void increment() { a += 10; } Only one thread at a time can execute this method on the same instance  no interleaving possible (“atomic action”)  no inconsistencies but: beware of inefficiencies/deadlocks

Higher level: java.util.concurrent Lots of useful high-level stuff for concurrency: E.g. Thread pools: –Threads use quite some resources (especially memory) –Pools limit the number of threads, queue requests for more threads/computation –Degrade more gracefully under high load

Thread pools java.util.concurrent.Executors. newFixedThreadPool(int poolSize) creates an ExecutorService of n threadsjava.util.concurrent.Executors. Good default: poolSize = number of cores submit(Runnable task) returns a Futuresubmit Must explicitly shutdown() ExecutorService

Runnable / Callable / Future Future is a “Wrapper” representing the future value of the thread’s computation Access with get(), will block until thread is finished => easy synchronisation Runnable’s run() method returns only void Callable’s call() method can return any Object, but does not take arguments => use constructor to “pass in” arguments

Code example int poolSize = 4; ExecutorService pool = Executors.newFixedThreadPool(poolSize); List > results = new ArrayList >(); for (int i = 0; i < max; i++) { results.add(pool.submit(new SomeComputation(i))); } // wait until all are finished and collect results: double total = 0.0; for (Future f: results) total += f.get(); pool.shutdown();

Cont. public class SomeComputation implements Callable { private int offset = -1; public SomeComputation(int offset) { this.offset = offset; } public Double call() { // some computation using “offset” // safe “atomic” output synchronized (System.out) { System.out.println(”someComputation offset = “ + offset + “ “ + someMessage); } return someResult; }

java.util.concurrent.atomic Thread-safe “atomic” access for certain objects and references E.g. AtomicInteger int addAndGet(delta)addAndGet Atomically adds the given value to the current value and returns result. [see also concurrent versions of collections] [synchronization can be expensive, can lead to deadlocks and similar, avoid, or replace with high-level constructs]