Threads some important concepts Simon Lynch

Slides:



Advertisements
Similar presentations
13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Concurrency 101 Shared state. Part 1: General Concepts 2.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
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.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
1 Thread Pools Representation and Management of Data on the Internet.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
Internet Software Development More stuff on Threads Paul Krause.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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.
Internet Software Development Controlling Threads Paul J Krause.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Threading Eriq Muhammad Adams J
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
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.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 24 th, 2010 The University of Georgia.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
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.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
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 and Garbage Collection Session 16.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
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.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
Distributed and Parallel Processing George Wells.
Java Thread Programming
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Multi Threading.
Thread Pools (Worker Queues) cs
Practice Session 8 Lockfree LinkedList Blocking queues
EE 422C Multithreading & Parallel Programming
Threads Chate Patanothai.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Computer Science 2 06A-Java Multithreading
Threads in Java James Brucker.
Threads and Multithreading
some important concepts
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

threads some important concepts Simon Lynch

issues the Thread class & Runnable interface interleaving problems locks synchronization problems with locks wait & notify

the thread problem the Thread class & Runnable interface - start & run methods the problem with multiple Threads – “interleaving” - control switches from one thread to another at inconvenient times, eg... // draw blue oval setColor ( blue ) fillOval(... ) //draw green square setColor (green ) fillRect(... )

synchronisation synchronisation sets up thread locks... locks (intrinsic lock aka monitor lock aka monitor) - stop chunks of code being interrupted so… …stop threads interleaving acquiring & releasing locks (& write-back) happens automatically with synchronisation NB: some problems with locks (deadlock, starvation, livelock) read... docs.oracle.com/javase/tutorial/essential/concurrency/starvelive.html docs.oracle.com/javase/tutorial/essential/concurrency/starvelive.html can synchronise with methods, objects (& classes - kinda)

synchronising methods synchronising instance methods......or static (class) methods careful because... 1.they synch the object they run on (may not be what you intend) 2.object references can “leak” – adding a reference to some (unsynch’d) structure before something synch’d has completed 3.you cannot synch constructors read...

synchronising code blocks public class SynchBlob2 extends AbstractBlob implements Runnable { static Object lock = new Object(); public void run() {display(); while( notDeadYet() ) {snooze(); synchronized(lock) {erase(); age(); if( notDeadYet() ) {move(); display(); }

monitors Monitors are the objects which synchronization occurs over. Java states that... "a thread becomes the owner of the object's monitor in one of three ways: 1.by executing a synchronized instance method of that object. 2.by executing the body of a synchronized statement that synchronizes on the object. 3.for objects of type Class, by executing a synchronized static method of that class" NB: Only one thread at a time can own an object's monitor.

wait & notify public class ProdCom { private Object next; private boolean empty = true; public synchronized Object get() {while (empty) {try {wait(); } catch (InterruptedException e) {} } empty = true; notifyAll(); return next; } public synchronized void put(Object x) {while (!empty) {try {wait(); } catch (InterruptedException e) {} } empty = false; next = x; notifyAll(); }

wait & notify check Java API Object docs for... wait() & wait(long) notify() & notifyAll() NB: 1.these methods should only be called by a thread that owns the object's monitor 2.java says... "interrupts and spurious wakeups are possible" so wrap calls within a suitable condition 3.remember to catch the InterruptedException

also… LinkedBlockingQueue an AJProgrammers shortcut(?) void put(E e) E take() …and all the stuff from… BlockingQueue Queue Collection …etc

thread pools ExecutorService pool = Executors.newFixedThreadPool(poolSize); while ( stillActiveJobsArriving ) { Runnable task = getNextRunnable(); pool.execute(task); } pool.shutdown(); // finish tasks then shut down // Wait until all threads are finish pool.awaitTermination( 5, TimeUnit.SECONDS )

callables what if you want values from your threads/runnables? use Callable tasks with executors & futures (easier than it seems!) eg... public class MyTask implements Callable public SomeType call() {... blah... return something of SomeType }... }

callables – part 2… ExecutorService executor =...make some ExecutorService... Future future = executor.submit(new MyTask());...do some stuff maybe, then... try { SomeType result = future.get();...do something with result... } catch (ExecutionException ex) { clean up as required }

or use FutureTask… FutureTask future = new FutureTask (new MyTask()); executor.execute(future); try { SomeType result = future.get();...do something with result... } catch (ExecutionException ex) { clean up as required }

thread pool workloading this discussion is Java specific… a ThreadPool has 5 worker threads and is given 20 tasks to service; each task runs a loop which performs a Thread.sleep(ms). 1.hypothesise the threading behaviour. 2.how could you test your hypothesis? 3.how difficult would it be to write a new threading API to provide a different behaviour?

other issues How to test multi-threaded programs… … to be discussed later in lab sessions Thread.join() allows one thread to wait for the completion of another someOtherThread.join(); …causes the current thread to wait until someOtherThread terminates

other issues “happens-before” When a statement invokes Thread.start, every statement that has a happens-before relationship with that statement also has a happens- before relationship with every statement executed by the new thread. When a thread terminates and causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join.

volatiles #1 class Test { static int i = 0, j = 0; static void one() { i++; j++; } static void two() { System.out.println("i=" + i + " j=" + j); } } two threads t1, t2. t1 repeatedly calls Test.one() t1 repeatedly calls Test.two() sometimes t2 will print values such that j > i examples from…

volatiles #2 class Test { static int i = 0, j = 0; static synchronized void one() { i++; j++; } static synchronized void two() { System.out.println("i=" + i + " j=" + j); } } one way to solve the problem examples from…

volatiles #3 class Test { static volatile int i = 0, j = 0; static void one() { i++; j++; } static void two() { System.out.println("i=" + i + " j=" + j); } } another way to solve the problem volatile guarantees that access to shared values for i and j occur in the same order during execution of each thread examples from…

threads interleaving threads memory consistency “happens-before” synchronising methods of a class but object references can “leak” – adding a reference to some (unsynchronised) structure before something synchronised has completed locks (intrinsic lock aka monitor lock aka monitor) acquiring & releasing locks (NB: When a thread releases a lock, happens-before established with any subsequent acquisition of the same lock) deadlock, starvation & livelock implication of “static” synchronised methods wait & notify & notifyAll to read