CS 159: Parallel Processing
|
|
- August Nelson
- 6 years ago
- Views:
Transcription
1 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 concurrency objects Reference: index.html Processes and Threads A process is basically a self"contained execution environment Speci#cally: a process has its own memory space Threads are $lightweight% processes Threads exist within processes. Each process has at least one. Threads share the process&s resources including memory and open #les Thread Objects Each Thread is associated with an instance of the Thread class. The most straightforward way to create a thread is to instantiate a Thread object each time the application needs to initiate an asynchronous task. You can use an Executor to create or utilize pre"existing threads for you. You hand over the tasks that are required to be done.
2 First technique: De#ning and Starting a Thread define a Runnable object (the Runnable interface defines a single method, run): public class HelloRunnable implements Runnable public void run() System.out.println("Hello from a thread"); public static void main(string args[]) (new Thread(new HelloRunnable())).start(); De#ning and Starting a Thread Second technique: subclass the Thread class public class HelloThread extends Thread public void run() System.out.println("Hello from a thread"); public static void main(string args[]) (new HelloThread()).start(); The first technique is more general since your class can subclass anything, not just Thread. The sleep method of the Thread class The Thread class has a static method called sleep that will place the currently executing thread into a sleep state 'execution suspended( for a speci#c period of time. If one thread is interrupted while it is sleeping, an InterruptedException will be thrown by the sleep method of the sleeping thread. Interrupts You can interrupt a thread by invoking the interrupt method on the Thread object. For this to work properly, the interrupted thread must support its own interuption. This can be done: (a) by catching the InterruptedException---if the methods that throw the exception are often being called; (b) by checking if an interrupt has been received---if a long time can go by without calling a method that throws an InterruptedException. This is done by calling Thread.interrupted() which returns true if an interrupt has been received.
3 Sleep example public class SleepMessages public static void main(string args[]) throws InterruptedException String importantinfo[] = "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" ; for (int i = 0; i < importantinfo.length; i++) //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); Interrupt example for (int i = 0; i < inputs.length; i++) heavycrunch(inputs[i]); //--assume a long compute time if (Thread.interrupted()) //We've been interrupted: no more crunching. return; The need for synchronization Things that can go wrong...thread interference when more than a single thread accesses shared data, there is the possibility for errors...interleaved operations may result in strange results...example of Counter object. class Counter private int c = 0; public void increment() c++; public void decrement() c--; public int value() return c; Memory consistency errors...cache memory consistency issues programmer must ensure the $happens"before% relationship example: int counter = 0; later: counter++; println(counter); if more than one thread accesses counter, then as long as we can ensure that counter++ happens before println(counter) in another thread, then the program produces the correct value.
4 More on the happens"before relationship when one thread invokes the Thread.start method, every statement that has a happens"before relationship with this statement will have a happens"before relationship with every statement executed in the new thread. Synchronization In Java, there are two synchronization mechanisms: method synchronization statement synchronization. method synchronization is achieved through the synchronized keyword. One thread at a time can enter a synchronized method. See: When one thread exits a synchronized method, all subsequent threads are guaranteed that a happensbefore relationship exists with statements executed by the #rst thread on the same object. Example public class SynchronizedCounter private int c = 0; public synchronized void increment() c++; public synchronized void decrement() c--; public synchronized int value() return c; So one way to prevent thread interference and ensure memory consistency is to handle all reads and writes of shared variables through synchronized methods. This can be inefficient. Intrinsic Locks and Synchronization Synchronization is achieved through the use of locks known as intrinsic locks or monitor locks. Every object has an intrinsic lock. If one thread wants to access an object&s #elds in an exclusive and consistent manner, it must acquire that object&s intrinsic lock before accessing the #elds and then releasing the lock after it is done. While one thread $owns% an object&s intrinsic lock, no other thread can access it.
5 Synchronized methods When a synchronized method is invoked by a thread, that thread acquires the intrinsic lock of the method&s object. The lock is released when the thread exits the method 'even through an un"caught exception(. Synchronized statements Synchronized statements are achieved by acquiring the intrinsic lock on a speci#ed object. These are synchronized Example: public void addname(string name) synchronized(this) lastname = name; namecount++; namelist.add(name); This one is not Another Example What about recursion? These objects are just for providing intrinsic locks public class TwoCounters private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); A thread cannot acquire a lock that is owned by another thread. public void inc1() synchronized(lock1) c1++; public void inc2() synchronized(lock2) c2++; It can, however, re"acquire a lock that it already owns. This is called reentrant synchronization.
6 Atomic Access Reads and writes of reference variables and nearly all primitive type variables are atomic. Reads and writes of all variables declared volatile are atomic. Any write to a volatile variable creates a happens"before relationship with subsequent reads of that variable. Liveness The ability of a concurrent application to execute in a timely manner is known as its "liveness". Problems with liveness include "deadlock", "starvation", and "livelock". Deadlock: two threads each waiting for the other (or more complex multi-way links between threads). Starvation: shared resource is held by a greedy thread thereby not allowing other threads that need access to the resource to proceed. Livelock: a thread acts in response to another...who acts in response to the first. The actions prevent either thread from proceeding as each continues to try to respond the other indefinitely. They're not blocked...just doing useless work. Guarded Blocks Here&s a synchronization technique that provides an e)cient way to access a shared resource. The variable $joy% is set to true by some other thread. public synchronized guardedjoy() //--This guard only loops once for each special event, //--which may not be the event we're waiting for. while(joy) try wait(); catch (InterruptedException e) System.out.println( "Joy and efficiency have been achieved"); How it works The thread that has acquired the lock to the method's object finds that joy is false. The wait method releases the lock and blocks until another thread sends out notification that something has happened. The notifyall method reports to all threads waiting on the intrinsic lock owned by the notifying object which cause them to awaken. For example, this would be what the code in the notifying thread might look like: public synchronized notifyjoy() joy = true; notifyall();
7 An application to a consumer"producer problem The problem: the producer thread generates a product 'in this case a message string( that is consumed by another thread. What&s the di)culty? the consumer cannot attempt to use the product until the producer has generated it. the producer cannot place a new product in the bu*er where the consumer retrieves it until the consumer has removed it The Drop class The Drop class represents the location where the producer leaves the product and the consumer picks it up. One #eld: boolean empty; This #eld is true if there is no product waiting to be picked up by the consumer and false if there is a product Two methods: public synchronized String take() public synchronized void put(string message) See: Drop.java The String is the product that is produced and consumed. The Producer class The Consumer class The Producer class represents the entity that generates the product. One #eld: Drop drop; //--where to leave the product The class implements the Runnable interface One method: public void run() The Consumer class represents the entity that consumes the product. One #eld: Drop drop; //--where to get the product The class implements the Runnable interface One method: public void run() See: Producer.java See: Consumer.java
8 The Program Immutable Objects public class ProducerConsumerExample public static void main(string[] args) Drop drop = new Drop(); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); Immutable objects are useful in concurrent applications because, since their state cannot change, they cannot become corrupted by multiple threads accessing them concurrently. Here&s an example. the class SynchronizedRGB represents a color. objects of this class have three color components 'red, green, blue( and a name 'e.g. $pitch black%( See: SynchronizedRGB.java Example Example 'continued( It is possible for an object of the SynchronizedRGB class to appear to be in an inconsistent state 'although it will always be in a consistent state(. Suppose, for example, a thread executes the following code: SynchronizedRGB color = new SynchronizedRGB(0, 0, 0, "Pitch Black");... int mycolorint = color.getrgb(); //Statement 1 String mycolorname = color.getname(); //Statement 2 Suppose another thread modi#es the color object by invoking color.set after Statement 1 but before Statement 2. Then the value of mycolorint will be inconsistent with mycolorname. One way to avoid this is to bind the two statements together in a synchronized statement: synchronized (color) int mycolorint = color.getrgb(); String mycolorname = color.getname(); If color was immutable, then this could not happen.
9 A Strategy for De#ning Immutable Objects 1. Don&t provide $setter% methods + methods that modify #elds or objects referred to by #elds. 2. Make all #elds #nal and private. 3. Don&t allow subclasses to override methods. The simplest way to do this is to declare the class as #nal. A more sophisticated approach is to make the constructor private and construct instances in factory methods. The strategy 'continued( 4. If the instance #elds include references to mutable objects, don&t allow those objects to be changed: Don&t provide methods that modify the mutable objects. Don&t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. Applying the strategy If we apply this strategy to the SynchronizedRGB class: 1. There are two setter methods in this class. The #rst one, set, arbitrarily transforms the object, and has no place in an immutable version of the class. The second one, invert, can be adapted by having it create a new object instead of modifying the existing one. 2. All #elds are already private; they are further quali#ed as #nal. 3. The class itself is declared #nal. 4. Only one #eld refers to an object, and that object is itself immutable. Therefore, no safeguards against changing the state of $contained% mutable objects are necessary. High"level Concurrency Objects Executors Java 5.0 allows us to,re"use& threads so that it&s not one thread tied to one task. Executors allow us to separate thread management from thread creation. Executor Interfaces The Executor interface has one method: voidexecute(runnable command) This method executes the given command at some time in the future. See: SynchronizedRGB.java
10 Working with Executors If r is a Runnable object, and e is an Executor object you can replace (new Thread(r)).start(); with e.execute(r); Executor implementations often rely on the presence of thread pools which are worker threads. A simple way to create an executor that uses a #xed thread pool is to invoke the newfixedthreadpool factory method in java.util.concurrent.executors For more information see the reference at Sun Microsystems: exinter.html
Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency
Java Threads Vs Processes CS6868 - Concurrent Programming Java Concurrency V. Krishna Nandivada Typically each instance of JVM creates a single process. Each process creates one or more threads. Main thread
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 informationRecapitulation of basics. Concurrent Programming in Java. Java Threads. Managing Thread objects. Concurrent Thread Execution. Starting a Thread (1)
Concurrent Programming in Java bhik Roychoudhury CS 3211 National University of Singapore Recapitulation of basics Concurrency concepts Threads / Processes structuring mechanism Different from procedures
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 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 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 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 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 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 informationWeek 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 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 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 informationContribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team
http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples
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 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 informationFaculty of Computers & Information Computer Science Department
Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process
More informationConcurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
Concurrency in Object Oriented Programs 1 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Concurrency: the Future of Computing Java Concurrency Thread Safety
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 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 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 informationSSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)
SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics
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 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 informationRecap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.
Lecture 07: Advanced Thread programming Software System Components 2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Recap How to deal with race condition in Java Using synchronised
More informationIntroduction 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 informationChair 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 informationThreads Synchronization
Synchronization Threads Synchronization Threads share memory so communication can be based on shared references. This is a very effective way to communicate but is prone to two types of errors: Interference
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 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 informationCS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers
CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some
More informationNeed for synchronization: If threads comprise parts of our software systems, then they must communicate.
Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.
More informationLecture 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 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 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 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 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 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 informationSystem 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 informationSynchronization 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 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 informationSynchronization. CS 475, Spring 2018 Concurrent & Distributed Systems
Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4
More informationCOMP 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 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 informationShared Objects & Mutual Exclusion
Feb. 08, 2012 Concurrent Execution Concepts Process interference Mutual exclusion Models Model checking for interference Modeling mutual exclusion Practice Multithreaded Java programs Thread interference
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 informationPerformance Throughput Utilization of system resources
Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency
More informationCOE518 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 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 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 informationConcurrency in Java Prof. Stephen A. Edwards
Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for
More informationProgramming Language Concepts: Lecture 11
Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]
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 informationTHREADS & CONCURRENCY
4/26/16 Announcements BRING YOUR CORNELL ID TO THE PRELIM. 2 You need it to get in THREADS & CONCURRENCY Prelim 2 is next Tonight BRING YOUR CORNELL ID! A7 is due Thursday. Our Heap.java: on Piazza (A7
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 informationProblems 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 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 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 informationTHREADS 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 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 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 informationConcurrency in Object Oriented Programs 4. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
Concurrency in Object Oriented Programs 4 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Thread Control Tasks and Task Control Finding and Exploiting Parallelism
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 informationCS61B, 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 informationCOMPSCI 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 informationThreads 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 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 informationCMSC 433 Programming Language Technologies and Paradigms. Composing Objects
CMSC 433 Programming Language Technologies and Paradigms Composing Objects Composing Objects To build systems we often need to Create thread safe objects Compose them in ways that meet requirements while
More informationMultiple 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 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 informationComponent-Based Software Engineering
Component-Based Software Engineering More stuff on Threads Paul Krause Lecture 7 - Contents Basics of threads and synchronization Waiting - releasing locks Collection Plate example Choices when pausing
More informationMultithread Computing
Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread
More informationTHREADS & CONCURRENCY
27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late
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 informationPart I: Communication and Networking
Review what we learned Part I: Communication and Networking Communication and Networking: Week 5-6, Lectures 2-7 Lecture 1 OSI vs TCP/IP model OSI model Protocols TCP/IP model Application FTP SMTP HTTP
More informationG51PGP 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 informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationJava 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 informationJAVA 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 informationThe Java Memory Model
The Java Memory Model What is it and why would I want one? Jörg Domaschka. ART Group, Institute for Distributed Systems Ulm University, Germany December 14, 2009 public class WhatDoIPrint{ static int x
More informationCMSC 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 informationExercise 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 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 informationComputation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.
CMSC 330: Organization of Programming Languages Threads Computation Abstractions t1 t2 t1 t3 t2 t1 p1 p2 p3 p4 CPU 1 CPU 2 A computer t4 t5 Processes (e.g., JVM s) Threads CMSC 330 2 Processes vs. Threads
More informationAn 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 informationQuestion 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 informationBackground. vanilladb.org
Background vanilladb.org Why do you need a database system? 2 To store data, why not just use a file system? 3 Advantages of a Database System It answers queries fast Q1: among a set of blog pages, find
More informationCS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey
CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Threads block when they can t get that lock Wanna have your threads stall? Go ahead, synchronize it all The antidote to this liveness pitfall? Keeping
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 informationExercise 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 informationMonitors; Software Transactional Memory
Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico March 17, 2016 CPD (DEI / IST) Parallel and Distributed
More informationDefinition: A thread is a single sequential flow of control within a program.
What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.
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 informationMultithreading 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 informationConcurrency: a crash course
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Concurrency: a crash course Concurrent computing Applications designed as a collection of computational units that may execute
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 informationPart 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 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 informationCISC 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 informationShared-Memory and Multithread Programming
Shared-Memory and Multithread Programming Pruet Boonma pruet@eng.cmu.ac.th Department of Computer Engineering Faculty of Engineering, Chiang Mai University Based on a material by: Bryan Carpenter Pervasive
More informationF. 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