Concurrency. Fundamentals of Computer Science

Size: px
Start display at page:

Download "Concurrency. Fundamentals of Computer Science"

Transcription

1 Concurrency Fundamentals of Computer Science

2 Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at the same time (multiple cores) Concurrency issues The dark side of threading Unpredictability of thread scheduler Protecting shared data: synchronized methods Deadlock The really dark side of threading

3 Review: Creating & Starting a Thread public class BlastOff implements Runnable public void run() for (int i = 10; i > 0; i--) System.out.print(i + " "); System.out.println("BLAST OFF!"); public class Launch public static void main(string [] args) System.out.println("prepare for launch"); Thread thread = new Thread(new BlastOff()); thread.start(); System.out.println("done with launch"); % java Launch prepare for launch done with launch BLAST OFF! % java Launch prepare for launch 10 9 done with launch BLAST OFF! % java Launch prepare for launch 10 done with launch BLAST OFF!

4 Review: Multithreading for Speed Goal: Count how often different integers occur In a large array of integers Randomly generated in [0, 100) Have one thread handle each target integer % java ParallelSearch Starting workers... Count of 2 = 9888 Count of 7 = Count of 16 = 9989 Count of 42 = Count of 99 = 9894

5 public class SearchWorker implements Runnable private int target = 0; private int [] data = null; private int result = 0; public SearchWorker(int target, int [] data) this.target = target; this.data = data; public int getresult() return result; public int gettarget() return target; public void run() for (int i = 0; i < data.length; i++) if (data[i] == target) result++; Worker object: One of these is created for each target integer we want to search for. Needs to keep track of its input: what number to search for, the array to search in. Must remember its output: count of the target in the array.

6 ... final int DATA_SIZE = Integer.parseInt(args[0]); final int WORKERS = args.length - 1; int [] data = new int[data_size]; for (int i = 0; i < DATA_SIZE; i++) data[i] = (int) (Math.random() * 100); SearchWorker [] workers = new SearchWorker[WORKERS]; Thread [] threads = new Thread[WORKERS]; for (int i = 0; i < WORKERS; i++) workers[i] = new SearchWorker(Integer.parseInt(args[i + 1]), data); threads[i] = new Thread(workers[i]); threads[i].start(); for (int i = 0; i < WORKERS; i++) try threads[i].join(); catch (InterruptedException e) e.printstacktrace(); System.out.printf("Count of %d = %d\n",... Client program: 1. Parses command line arguments. 2. Creates random array of data to search in. 3. Creates each worker, launches each worker in its own thread. 4. Waits for each thread to finish, printing out the worker s result. workers[i].gettarget(), workers[i].getresult());

7 Trouble in Concurrency City: Act 1 Lost update problem Multiple threads All sharing a single counter object Each thread increments fixed number of times public class Count private int count = 0; public int getcount() return count; public class IncrementWorker implements Runnable private Count count = null; public IncrementWorker(Count count) this.count = count; public void increment() count++; public void run() for (int i = 0; i < 1000; i++) count.increment();

8 Lost Update Problem... Count count = new Count(); Thread [] threads = new Thread[N]; for (int i = 0; i < N; i++) threads[i] = new Thread(new IncrementWorker(count)); threads[i].start(); for (int i = 0; i < N; i++) try threads[i].join(); catch (InterruptedException e) e.printstacktrace(); System.out.println("Final count = " + count.getcount());... % java Increment 1 Final count = 1000 % java Increment 2 Final count = 2000 % java Increment 20 Final count = % java Increment 20 Final count = % java Increment 20 Final count = 19014

9 Synchronizing Methods Only allow 1 worker in increment at a time! Tell Java this using synchronized keyword public class Count private int count = 0; public int getcount() return count; public synchronized void increment() count++; % java Increment 20 Final count = % java Increment 20 Final count = % java Increment 20 Final count = 20000

10 Locking an Object Each object instance has a lock Multiple methods can be marked synchronized Only one can be executing at any time Locking is on the object level On the instance of the class, not the class data type itself Locking and unlocking takes time Only synchronize methods if necessary public void run() for (int i = 0; i < 1000; i++) synchronized (count) count.increment(); Another approach to fixing the lost update problem. Synchronization can be enforced on a block of code instead of an entire method.

11 Trouble in Concurrency City: Act 2 Concurrent access to same data structure Many built-in containers are not thread-safe! e.g. ArrayList, HashMap Program will crash (probably) Protect all reading/writing to shared structure Via synchronized method or synchronized code block

12 public class ArrayListBad implements Runnable private static ArrayList<Integer> list = new ArrayList<Integer>(); public void run() for (int i = 0; i < 10; i++) list.add((int) (Math.random() * 100)); System.out.println("Thread all done..."); public static void main(string[] args) Thread t1 = new Thread(new ArrayListBad()); t1.start(); Thread t2 = new Thread(new ArrayListBad()); t2.start(); try t1.join(); t2.join(); catch (InterruptedException e) e.printstacktrace(); System.out.println("Phew, we made it!"); May sometimes work, especially if loop in run() is short. But most likely you ll get some sort of exception: Exception in thread "Thread-1" Thread all done... java.lang.arrayindexoutofboundsexception: 15 at java.util.arraylist.add(unknown Source) at ArrayListBad.run(ArrayListBad.java:12) at java.lang.thread.run(unknown Source) Phew, we made it! 12

13 public class ArrayListGood implements Runnable private static ArrayList<Integer> list = new ArrayList<Integer>(); public void run() for (int i = 0; i < ; i++) synchronized(list) list.add((int) (Math.random() * 100)); System.out.println("Thread all done...");... Adding synchronized block protects the shared static list instance variable, now only one thread is allowed to add to the list at any point in time. 13

14 Trouble in Concurrency City: Act 3 Deadlock Program stops doing anything useful All you need is 2 objects and 2 threads

15 Summary Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at the same time (multiple cores) Concurrency issues The dark side of threading Unpredictability of thread scheduler Protecting shared data: synchronized methods Deadlock The really dark side of threading

16 Your Turn Goal: Increment/decrement all ints in an array Create class NumHolder that implements Runnable, holds array of 100 ints Create increment() and decrement() methods Methods that go through all 100 integers and ++ or -- them Create run() method Loop 1000 times, each loop flip coin and call either increment() or decrement() Create main program in NumHolderLaunch Create a single NumHolder object Create two threads, passing them the NumHolder object you created Print out NumHolder object Start threads, wait for them to finish Print out NumHolder again Hint: All numbers should be the same in the second print of NumHolder Open Moodle, go to CSCI 136, Section 01 Open the dropbox Concurrency Issues In-Class Asmt Drag and drop your program file to the Moodle dropbox You get: 1 point if you turn in something, 2 points if you turn in something that is correct.

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Concurrency.   CSCI 136: Fundamentals of Computer Science II Keith Vertanen Concurrency http://csunplugged.org/routing-and-deadlock CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Multi-threaded programs Multiple simultaneous paths of execution Seemingly

More information

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues Michele Van Dyne MUS 204B mvandyne@mtech.edu https://katie.mtech.edu/classes/csci136 Concurrency Issues Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core)

More information

Threads. Fundamentals of Computer Science

Threads. Fundamentals of Computer Science Threads Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at the same time (multiple cores) Why? Get work

More information

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Threads

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Threads Michele Van Dyne MUS 204B mvandyne@mtech.edu https://katie.mtech.edu/classes/csci136 Threads Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually at

More information

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

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 5 problems on the following 7 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

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

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2012 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2012 Name: This exam consists of 5 problems on the following 8 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

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

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2012 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2012 Name: This exam consists of 5 problems on the following 8 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

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

Contents. 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 information

Outline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST)

Outline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST) i219 Software Design Methodology 10. Multithreaded programming Kazuhiro Ogata (JAIST) Outline of lecture 2 Thread Race condition Synchronization Deadlock Bounded buffer problem Thread (1) 3 Units of execution.

More information

Principles of Software Construction: Concurrency, Part 1

Principles of Software Construction: Concurrency, Part 1 Principles of Software Construction: Concurrency, Part 1 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Midterm review tomorrow 7-9pm Midterm on Thursday If you re still looking for

More information

CS18000: Programming I

CS18000: Programming I CS18000: Programming I Synchronization 22 February, 2010 Prof. Chris Clifton Concurrency Example: Banking class ATM { public void withdrawcash(acct a) { Scanner sc = new Scanner(System.in); int amount

More information

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture 2 Concurrency Model checking Java Pathfinder (JPF) Detecting race condition Bounded buffer problem

More information

Recursion. Fundamentals of Computer Science

Recursion. Fundamentals of Computer Science Recursion Fundamentals of Computer Science Outline Recursion A method calling itself All good recursion must come to an end A powerful tool in computer science Allows writing elegant and easy to understand

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

Lecture 35. Threads. Reading for next time: Big Java What is a Thread? Lecture 35 Threads Reading for next time: Big Java 21.4 What is a Thread? Imagine a Java program that is reading large files over the Internet from several different servers (or getting data from several

More information

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

CMSC 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 information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Synchronization in Java Department of Computer Science University of Maryland, College Park Multithreading Overview Motivation & background Threads Creating Java

More information

Question Points Score Total 100

Question Points Score Total 100 Midterm Exam #1 CMSC 433 Programming Language Technologies and Paradigms Spring 2014 March 13, 2014 Guidelines Put your name on each page before starting the exam. Write your answers directly on the exam

More information

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Network 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 information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

CONDITIONAL EXECUTION

CONDITIONAL EXECUTION CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd)

Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd) Processes and Threads Industrial Programming Lecture 5: C# Threading Introduction, Accessing Shared Resources Based on: An Introduction to programming with C# Threads By Andrew Birrell, Microsoft, 2005

More information

F. Tip and M. Weintraub CONCURRENCY

F. Tip and M. Weintraub CONCURRENCY F. Tip and M. Weintraub CONCURRENCY SHARED-MEMORY CONCURRENCY threads execute concurrently threads communicate values via shared memory synchronization using locks 2 PITFALLS data races atomicity violations

More information

7. MULTITHREDED PROGRAMMING

7. 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 information

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions? Project Threads Synchronization Minimum submission Deadline extended to tonight at midnight Early submitters 10 point bonus TSP Still due on Tuesday! Before we begin Plan for today Thread synchronization

More information

System Programming. Practical Session 4: Threads and Concurrency / Safety

System Programming. Practical Session 4: Threads and Concurrency / Safety System Programming Practical Session 4: Threads and Concurrency / Safety Using Threads - All the computer programs you've seen so far were sequential only one thing was performed at any given time - Sometimes

More information

Systems Programming & Scripting

Systems Programming & Scripting Systems Programming & Scripting Lecture 10: C# Threading Introduction, Accessing Shared Resources Based on: An Introduction to programming with C# Threads By Andrew Birrell, Microsoft, 2005 Examples from

More information

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

Multithreaded 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 information

Threads and Parallelism in Java

Threads 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

Concurrency CSCI 201 Principles of Software Development

Concurrency CSCI 201 Principles of Software Development Concurrency CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Synchronization Outline USC CSCI 201L Motivation for Synchronization Thread synchronization is used

More information

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing

More information

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, Instructions

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, Instructions Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 Name: Athena* User Name: Instructions This quiz is 50 minutes long. It contains 8 pages

More information

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors Howard Barringer Room KB2.20: email: Howard.Barringer@manchester.ac.uk February 2009 Outline Monitors FSP Models-to-Java Monitors Producers/Consumers

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

COE518 Lecture Notes Week 7 (Oct 17, 2011)

COE518 Lecture Notes Week 7 (Oct 17, 2011) coe518 (Operating Systems) Lecture Notes: Week 7 Page 1 of 10 COE518 Lecture Notes Week 7 (Oct 17, 2011) Topics multithreading in Java Note: Much of this material is based on http://download.oracle.com/javase/tutorial/essential/concurrency/

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation 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 information

Multithreading Pearson Education, Inc. All rights reserved.

Multithreading Pearson Education, Inc. All rights reserved. 1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads

More information

Principles of Software Construction: Concurrency, Part 1

Principles of Software Construction: Concurrency, Part 1 Principles of Software Construction: Concurrency, Part 1 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Midterm review tomorrow 7-9pm, HH B103 Midterm on Thursday HW 5 team signup

More information

Part IV Other Systems: I Java Threads

Part IV Other Systems: I Java Threads Part IV Other Systems: I Java Threads Spring 2019 C is quirky, flawed, and an enormous success. 1 Dennis M. Ritchie Java Threads: 1/6 Java has two ways to create threads: Create a new class derived from

More information

Single processor CPU. Memory I/O

Single processor CPU. Memory I/O Lec 17 Threads Single processor CPU Memory I/O Multi processes Eclipse PPT iclicker Multi processor CPU CPU Memory I/O Multi-core Core Core Core Core Processor Memory I/O Logical Cores Multi-threaded

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 Common Java Concurrency pitfalls Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 About me Seasoned software engineer primarily working in the area of Identity and access management. Spent

More information

Multiple Inheritance. Computer object can be viewed as

Multiple Inheritance. Computer object can be viewed as Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.

More information

Concurrency and Java Programming

Concurrency and Java Programming Concurrency and Java Programming What is Concurrent Programming? Concurrent programming involves using features of the Java VM that allow parts of your program to run in parallel with each other. This

More information

Introduction to Java Threads

Introduction 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 information

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION COMP 346 WINTER 2018 1 Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION REVIEW - MULTITHREADING MODELS 2 Some operating system provide a combined user level thread and Kernel level thread facility.

More information

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar JAVA CONCURRENCY FRAMEWORK Kaushik Kanetkar Old days One CPU, executing one single program at a time No overlap of work/processes Lots of slack time CPU not completely utilized What is Concurrency Concurrency

More information

Synchronization in Java

Synchronization in Java Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Synchronization Overview Unsufficient atomicity Data races Locks Deadlock Wait /

More information

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

Overview. 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 information

Introduction to Locks. Intrinsic Locks

Introduction to Locks. Intrinsic Locks CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Introduction to Locks Intrinsic Locks Atomic-looking operations Resources created for sequential code make certain assumptions, a large

More information

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

Reading from URL. Intent - open URL  get an input stream on the connection, and read from the input stream. Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)

More information

Concurrent Computing CSCI 201 Principles of Software Development

Concurrent 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 information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

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

Note: 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 information

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

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY Instructors: Crista Lopes Copyright Instructors. Basics Concurrent Programming More than one thing at a time Examples: Network server handling hundreds of clients

More information

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

Overview. 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 information

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Encapsulation, Publication, Escape Data Encapsulation One of the approaches in object-oriented programming is to use data encapsulation

More information

JAVA EXAMPLES - SOLVING DEADLOCK

JAVA EXAMPLES - SOLVING DEADLOCK JAVA EXAMPLES - SOLVING DEADLOCK http://www.tutorialspoint.com/javaexamples/thread_deadlock.htm Copyright tutorialspoint.com Problem Description: How to solve deadlock using thread? Solution: Following

More information

THREADS AND CONCURRENCY

THREADS AND CONCURRENCY THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on

More information

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

COMP 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 information

COMP346 Winter Tutorial 4 Synchronization Semaphores

COMP346 Winter Tutorial 4 Synchronization Semaphores COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated

More information

Threads Chate Patanothai

Threads 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 information

CS193k, Stanford Handout #8. Threads 3

CS193k, 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 information

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics

More information

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

Advanced 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 information

Principles of Software Construction: Concurrency, Part 2

Principles 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

Java 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. 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 information

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

Chair 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 information

CS 159: Parallel Processing

CS 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 information

JAVA - MULTITHREADING

JAVA - MULTITHREADING JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amultithreaded programming language which means we can develop mult it hreaded program

More information

Module - 4 Multi-Threaded Programming

Module - 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 information

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012 CMPSCI 187: Programming With Data Structures Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012 Concurrency and a Case Study Concurrency and Threads Example: Counter, Increase,

More information

Threads and Concurrency in Java

Threads and Concurrency in Java Threads and Concurrency in Java 1 Concurrency! What every computer engineer needs to know about concurrency: Concurrency is to untrained programmers as matches are to small children. It is all too easy

More information

Multithreaded Programming

Multithreaded 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 information

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

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 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 information

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006 This document provides a brief introduction to programming with threads in Java. I presume familiarity

More information

Synchronizers Latches & Barriers

Synchronizers Latches & Barriers Synchronizers Latches & Barriers Synchronizers A synchronizer is any object that coordinates the control of threads based on its state. The basic mechanisms in java.util.concurrent are: Latches: gate,

More information

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

Computation 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 information

Multithreading. A thread is a unit of control (stream of instructions) within a process.

Multithreading. A thread is a unit of control (stream of instructions) within a process. Multithreading A thread is a unit of control (stream of instructions) within a process. When a thread runs, it executes a function in the program. The process associated with a running program starts with

More information

Java Programming Lecture 23

Java Programming Lecture 23 Java Programming Lecture 23 Alice E. Fischer April 19, 2012 Alice E. Fischer () Java Programming - L23... 1/20 April 19, 2012 1 / 20 Outline 1 Thread Concepts Definition and Purpose 2 Java Threads Creation

More information

Software Practice 1 - Multithreading

Software Practice 1 - Multithreading Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 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 information

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

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015 CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 6 problems on the following 7 pages. You may use your single-sided handwritten 8 ½ x 11 note sheet during

More information

EXCEPTIONS. Fundamentals of Computer Science I

EXCEPTIONS. Fundamentals of Computer Science I EXCEPTIONS Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)

More information

CS11 Java. Fall Lecture 7

CS11 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 information

CSCD 330 Network Programming

CSCD 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 information

Lecture 9: Introduction to Monitors

Lecture 9: Introduction to Monitors COMP 150-CCP Concurrent Programming Lecture 9: Introduction to Monitors Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 14, 2008 Abstracting Locking Details Recall our discussion

More information

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

Problems with Concurrency

Problems with Concurrency with Concurrency February 14, 2012 1 / 27 s with concurrency race conditions deadlocks GUI source of s non-determinism deterministic execution model interleavings 2 / 27 General ideas Shared variable Shared

More information

CSCI 201L Written Exam #2. 10% of course grade

CSCI 201L Written Exam #2. 10% of course grade Name Final Score ID Extra Credit Section (circle one): MW 3:30-6:30 CSCI 201L Written Exam #2 10% of course grade 1. Anonymous Inner Classes In lecture we walked through the following: 1. Having two classes

More information

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax Lab report Project 3 Mihai Ene I have implemented the solution in Java. I have leveraged its threading mechanisms and concurrent API (i.e. concurrent package) in order to achieve the required functionality

More information