CS 351 Design of Large Programs Threads and Concurrency

Similar documents
Java s Implementation of Concurrency, and how to use it in our applications.

Java Threads. Written by John Bell for CS 342, Spring 2018

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

CS 159: Parallel Processing

Concurrent Programming using Threads

What is a thread anyway?

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

THREADS AND CONCURRENCY

Threads Chate Patanothai

CMSC 132: Object-Oriented Programming II. Threads in Java

Threads Questions Important Questions

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Java Threads. COMP 585 Noteset #2 1

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

7. MULTITHREDED PROGRAMMING

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

CS 351 Design of Large Programs Introduction to Multi-Threaded Programming in Java

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Java Threads. Introduction to Java Threads

Multi-threading in Java. Jeff HUANG

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Performance Throughput Utilization of system resources

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Chapter 32 Multithreading and Parallel Programming

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Introduction to Java Threads

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Advanced Concepts of Programming

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

Multithreaded Programming

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci


CS 556 Distributed Systems

CS180 Review. Recitation Week 15

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Multithread Computing

THREADS & CONCURRENCY

Faculty of Computers & Information Computer Science Department

Problems with Concurrency. February 19, 2014

Contents. 6-1 Copyright (c) N. Afshartous

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

Threads and Parallelism in Java

CMSC 330: Organization of Programming Languages

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

CS 251 Intermediate Programming Methods and More

Animation Part 2: MoveableShape interface & Multithreading

Definition: A thread is a single sequential flow of control within a program.

THREADS & CONCURRENCY

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

CS193k, Stanford Handout #8. Threads 3

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Object Oriented Programming. Week 10 Part 1 Threads

CS11 Java. Fall Lecture 7

Java Threads and intrinsic locks

Only one thread can own a specific monitor

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Program #3 - Airport Simulation

Threads, Concurrency, and Parallelism

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Concurrency in Java Prof. Stephen A. Edwards

Multithreaded Programming

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

Techniques of Java Programming: Concurrent Programming in Java

CmpSci 187: Programming with Data Structures Spring 2015

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

CS 251 Intermediate Programming Methods and Classes

Programming Language Concepts: Lecture 11

Synchronization in Concurrent Programming. Amit Gupta

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Java Programming Lecture 23

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

G52CON: Concepts of Concurrency

User Space Multithreading. Computer Science, University of Warwick

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CSCD 330 Network Programming

CST242 Concurrency Page 1

Chapters 5 and 6 Concurrency

Shared Objects & Mutual Exclusion

Overview of Java Threads (Part 2)

Multithreading using Java. Dr. Ferdin Joe John Joseph

Advanced Programming Concurrency

Unit - IV Multi-Threading

Multithreading and Interactive Programs

Multiple Inheritance. Computer object can be viewed as

Parallel & Concurrent Programming

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

UNIT V CONCURRENT PROGRAMMING

CMSC 330: Organization of Programming Languages

CSCD 330 Network Programming

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

CS 351 Design of Large Programs Sockets Example

Transcription:

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 APIs available in java.util.concurrent package

Processes vs Threads Processes Self-contained execution environment Each process has own memory space Communicate with other processes through interprocess communication (pipes, sockets, files, etc.) Threads Creating new thread requires fewer resources than an new process. Threads within same process share process s resources. Threads have shared heap, but separate stacks.

Thread objects Each thread is associated with in instance of Thread Two ways to create a new thread: Subclass Thread Implement Runnable interface and pass Runnable object to Thread constructor. In both cases, you ll implement run method to contain the code to be executed on the thread. Implementing Runnable is the more flexible approach.

Thread.sleep method The sleep method causes the current thread to suspend execution for a specified number of milliseconds. Sleep time is not guaranteed to be precise. (Limits of OS) Sleep period may be terminated by an interrupt.

Thread methods If I have initialized a Thread named mythread mythread.start() starts running mythread mythread.join() Pauses current thread until mythread terminates

Synchronized Methods public class SynchronizedCounter { private int c = 0; public synchronized void increment () { c ++; public synchronized int value () { return c; It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block until the first thread is done with the object.

Synchronized Blocks public void copyp ( Point destination ){ synchronized (p) { destination.x = p.x; destination.y = p.y; public void addp ()( int n) { synchronized (p) { p.x += n; p.y += n; Both synchronized blocks obtain lock on member variable p

Synchronized Methods vs Blocks Making a method synchronized is equivalent to wrapping method body in a synchronized(this) block. Synchronized blocks are more complicated, but offer finer grained synchronization than synchronized methods.

Liveness Problems Deadlock Threads are blocked forever waiting for each other. Starvation Thread cannot gain access to shared resources held by other greedy threads. Livelock Threads too busy responding to each other to actually make progress.

FibThreads: Worker (1/1) public static class Worker extends Thread { private final String name ; private long step = 0; private int x = 0; private int y = 1; private int z; private boolean keepgoing = true ; public Worker ( String name ) { this. name = name ; z = x + y; private synchronized void update () { step ++; if (z < 0) { // restart after overflow x = 0; y = 1; else { x = y; y = z; z = x + y;

FibThreads: Worker (2/2) public void quit () { keepgoing = false ; @Override public void run () { while ( keepgoing ) { update (); System. out. println ( name + " stopping at step " + step ); @Override public synchronized String tostring () { return name + " step " + step + ", x = " + x + ", y = " + y + ", z = " + z;

FibThreads: main public static void main ( String [] args ) throws InterruptedException { Worker [] workers = new Worker []{ new Worker ("A"), new Worker ("B") ; for ( Worker worker : workers ) { worker. start (); for ( int i = 0; i < 10; ++i) { System. out. println ("i = " + i); for ( Worker worker : workers ) { System. out. println ( worker ); Thread. sleep (1000); // Take a short nap for ( Worker worker : workers ) { worker. quit (); for ( Worker worker : workers ) { // wait until this thread has finished. worker. join (); System. out. println (" All workers are done. Goodbye.");

FibThreads: Why synchronized? update and tostring methods are synchronized What might happen if we didn t?

Producer/Consumer Pattern Producers and consumers run concurrently. Producer produces values and places them in a shared queue. Consumer removes values from queue and processes them. May be multiple producers, consumers, queues.

Producer/Consumer with BlockingQueue Could implement with any queue type and careful use of synchronized blocks, but there is an easier way. The java.util.concurrent.blockingqueue interface extends java.util.queue with methods that make current thread wait if necessary. put add item to queue (wait if no room) take remove next item from queue (wait if empty)

ProducerConsumer: Producer public static class Producer implements Runnable { private final String name ; private final BlockingQueue < Integer > queue ; public Producer ( String name, BlockingQueue < Integer > queue ) { this. name = name ; this. queue = queue ; @Override public void run () { System. out. println (" Start " + name ); try { for ( int i = 0; i < 20; i ++) { System. out. println ( name + " produces " + i); queue. put (i); System. out. println ( name + " is done producing "); catch ( InterruptedException e) { System. out. println ( name + " was interrupted ");

ProducerConsumer: Consumer public static class Consumer implements Runnable { private final String name ; private final BlockingQueue < Integer > queue ; public Consumer ( String name, BlockingQueue < Integer > queue ) { this. name = name ; this. queue = queue ; @Override public void run () { System. out. println (" Start " + name ); try { while ( true ) { int value = queue. take (); System. out. println ( name + " consumes " + value ); catch ( InterruptedException e) { System. out. print ( name + " was interrupted ");

ProducerConsumer: main public static void main ( String [] args ) throws InterruptedException { BlockingQueue < Integer > sharedqueue = new LinkedBlockingQueue < >(); Thread prodthread = new Thread ( new Producer ("P", sharedqueue )); Thread consthread = new Thread ( new Consumer ("C", sharedqueue )); prodthread. start (); consthread. start ();