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

Size: px
Start display at page:

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

Transcription

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

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 thread has its own program counter (pointing to the current instruction being executed) All threads in a process share the execution environment Advantages of threads Simpler program design More responsive programs Disadvantages Context switching overhead Increased resource consumption Concurrency and parallelism NetProg 6 2 Image source:

3 Image source: Multithreading Operating system support for multithreading Simplifies the application code Allows more complex program execution Different threads may share a single CPU Threads can be interrupted to allow another thread to run (preemptive scheduling) voluntarily give up control (e.g. when waiting for data from a socket) Different threads can run on different cores of a CPU Allows faster execution NetProg 6 3

4 Thread Risks Safety Threads need sufficient synchronization, because The ordering of operations is unpredictable: the compiler, processor and runtime can reorder and time actions as they see fit (as long as it does not affect the result within the thread) Threads can access and modify variables that other threads are using Liveness A thread should not get into a state that it cannot make forward progress Performance Runtime overhead (e.g. context switching, scheduling) Synchronization costs (e.g. data sharing, inhibited compiler optimization) 4

5 Thread Programming Most commonly called Concurrent Programming Basic issue: Data can be accessed by multiple threads simultaneously Aim: Protecting the data from uncontrolled concurrent access Basic solutions: Thread confinement: don t share state variables across threads Make state variables immutable Use synchronization when accessing state variables Thread safety: correct program operation (conforms with the specification) NetProg 6 5 Image source:

6 Threads and Communications Rationale Time lag between starting to listen to input and data actually arriving Blocking while waiting for input suspends a whole (single threaded) program Maintaining control while waiting for input Option 1: Synchronous communication Reader loops asking if data has arrived (e.g. available() ) Option 2: Asynchronous communication Callback: create a function to be invoked when data has arrived, and register the function with the operating system Using multiple threads Allows the blocking of one thread while other threads are running In general, threads of a task can execute at different speeds NetProg 6 6

7 Thread Lifecycle Thread attributes ID, Name, Priority, State Enum Thread.State NEW: the thread has not yet started RUNNABLE: thread executing in the JVM BLOCKED: waiting for the availability of an event or a resource WAITING: waiting indefinitely for another thread to perform a particular action TIMED_WAITING: similar to WAITING but time is limited TERMINATED NetProg 6 7 Image source:

8 Main Thread Methods Getting information about a thread currentthread() Returns a reference to the current thread getid() getname() getpriority() getstate() return the ID, name, priority and state of the current thread tostring() returns a string representation of the current thread Setting thread parameters setname() setpriority() setdaemon(boolean on) marks this thread as daemon or user thread Execution control start() the thread begins execution, the JVM calls the run method of this thread run() the Runnable object s run method is called sleep(long millisec) puts the current thread to sleep yield() indicates that the current thread is willing to yield its current use of a processor NetProg 6 8

9 Multiple Threads -Code Example public class Calculator implements Runnable { private int number; public Calculator(int number) { this.number = number; public void run() { for (int i = 1; i <= 10; i++) { System.out.printf("%s: %d * %d = %d\n", Thread. currentthread().getname(), number, i, i * number); class Main { public static void main(string[] args) { for (int i = 1; i <= 10; i++) { Calculator calculator = new Calculator(i); Thread thread = new Thread(calculator); thread.start(); NetProg 6 9

10 Code Example - Thread States Main : Status of Thread 0 : NEW Main : Status of Thread 1 : NEW Main : Status of Thread 2 : NEW Main : Status of Thread 3 : NEW Main : Status of Thread 4 : NEW Main : Status of Thread 5 : NEW Main : Status of Thread 6 : NEW Main : Status of Thread 7 : NEW Main : Status of Thread 8 : NEW Main : Status of Thread 9 : NEW Main : Id 9 - Thread 0 Main : Priority: 10 Main : Old State: NEW Main : New State: RUNNABLE Main : ************************************ Main : Id 10 - Thread 1 Main : Priority: 1 Main : Old State: NEW Main : New State: BLOCKED Main : ************************************ Main : Id 18 - Thread 9 Main : Priority: 1 Main : Old State: BLOCKED Main : New State: RUNNABLE Main : ************************************ Main : Id 18 - Thread 9 Main : Priority: 1 Main : Old State: RUNNABLE Main : New State: TERMINATED Main : ************************************ Main : Id 16 - Thread 7 Main : Priority: 1 Main : Old State: BLOCKED Main : New State: RUNNABLE Main : ************************************ Main : Id 16 - Thread 7 Main : Priority: 1 Main : Old State: RUNNABLE Main : New State: TERMINATED Main : ************************************ NetProg 6 10

11 Code to Print the Thread States import java.io.*; import java.lang.*; public class Calculator_info implements Runnable { private int number; public Calculator_info(int number) { this.number = number; public void run() { for (int i = 1; i <= 10; i++) { System.out.printf("%s: %d * %d = %d\n", Thread.currentThread().getName(), number, i, i * number); class Main_1 { public static void main(string[] args) { Thread threads[]=new Thread[10]; Thread.State status[]=new Thread.State[10]; for (int i = 0; i < 10; i++) { threads[i]=new Thread(new Calculator_info(i)); if ((i%2)==0){ threads[i].setpriority( Thread.MAX_PRIORITY); else { threads[i].setpriority( Thread.MIN_PRIORITY); threads[i].setname("thread "+i); 1/2 try { FileWriter file = new FileWriter("log.txt"); PrintWriter pw = new PrintWriter(file); for (int i=0; i<10; i++) { pw.println("main : Status of Thread " + i + " : " + threads[i].getstate()); status[i] = threads[i].getstate(); for (int i=0; i<10; i++){ threads[i].start(); boolean finish=false; while (!finish) { for (int i=0; i<10; i++){ if (threads[i].getstate()!=status[i]) { writethreadinfo(pw,threads[i],status[i]); status[i]=threads[i].getstate(); finish=true; for (int i=0; i<10; i++){ finish=finish && (threads[i].getstate()==java.lang.thread.state.terminated); pw.close(); catch(ioexception e){ private static void writethreadinfo(printwriter pw, Thread thread, java.lang.thread.state state) { pw.printf("main : Id %d - %s\n", thread.getid(),thread.getname()); pw.printf("main : Priority: %d\n",thread.getpriority()); pw.printf("main : Old State: %s\n",state); pw.printf("main : New State: %s\n",thread.getstate()); pw.printf("main : ************************************\n"); 2/2 NetProg 6 11

12 Returning Information from a Thread (1) The run() and start() methods do not return anything Solution: Using accessor (getter) methods Steps Store the result in a field private to the thread Invoke the getter method Key point: The thread s run method has to finish with the data before the accessor method is invoked NetProg 6 12

13 Returning Information from a Thread (2) There is no guarantee that one thread will be faster/slower than another If you call the getter method too early, the result may not be ready Polling The getter method returns a flag value (or throws an exception) if the result is not ready yet Problem: inefficient, repeatedly calls the getter method Even bigger problem: The main program usually has higher priority and may not allow the thread to run at all Callbacks When the thread finishes, it invokes a method in the main class The last step in the run method is invoking a method in the main program with the result Main program Start the thread Thread NetProg 6 13 Callback

14 Callback Example Code Excerpt public class CallbackDigest implements Runnable { private String filename; public CallbackDigest(String filename) { this.filename = public void run() { try { // Calculate the digest byte[] digest = sha.digest(); CallbackDigestUserInterface.receiveDigest(digest, filename); catch (IOException ex) { System.err.println(ex); catch (NoSuchAlgorithmException ex) { System.err.println(ex); Callback public class CallbackDigestUserInterface { public static void receivedigest(byte[] digest, String name) { StringBuilder result = new StringBuilder(name); result.append(": "); result.append(datatypeconverter.printhexbinary(digest)); System.out.println(result); public static void main(string[] args) { for (String filename : args) { CallbackDigest cb = new CallbackDigest(filename); Thread t = new Thread(cb); t.start(); Thread Main program NetProg 6 For the full example, see the textbook Java Network Programming 14

15 Thread Cooperation Issues Thread interference If the following code is accessed by two threads at the same time, the value of c will depend on the interleaving of the two threads class Counter { private int c = 0; public void increment() { c = c + 1; public void decrement() { c = c -1 ; public int value() { return c; Memory consistency errors Different threads have different views Example: Lost update Thread 1 reads c Thread 2 reads c Thread 1 increments the retrieved value (result is 1) Thread 2 decrements the retrieved value (result is -1) Thread 1 stores its value c = 1 Thread 2 stores its value c = -1 Thread_1 s result has been lost of the same data NetProg 6 15

16 Race Conditions Definition: The correctness of a computation depends on the timing or interleaving of multiple threads Example: Lazy initialization Initialization of a variable is often postponed until the variable is used If two threads are using the same variable (e.g. a counter), multiple objects can be created instead one each thread may create an object Java provides several methods to avoid race conditions Synchronized execution Using the Volatile keyword Locks Atomic variables We look at some of them in this lecture NetProg 6 16

17 Thread Safety Code can be executed and shared in multithread environment and will behave as expected (no race conditions) Levels: thread safe, conditionally safe, not thread safe Thread-safe objects Immutable objects by default E.g. read-only and final variables Local variables Volatile keyword Guarantees visibility across threads public volatile int counter = 0; Data is always read from memory, not from CPU cache The reading and writing instructions of volatile data cannot be reordered by the JVM (e.g. for performance reasons) More expensive read and write operations Need caution Static variables (need a lot of caution!) NetProg 6 17

18 Resource Sharing Issues The scheduling of threads is unpredictable If a shared resource is used by many simultaneously, the result can be confusing E.g. lines (or even items) from different threads can get mixed up in a printout Exclusive access needs to be granted to certain resources (e.g. printers), so that no other thread can jump in NetProg 6 18 Image source:

19 Synchronization You can mark a group of statements to be executed without interruption It is called synchronization, and it works by locking the object for exclusive use Synchronization works only in the same JVM Synchronized method public synchronized void increment() { c = c + 1; The method has to complete before another thread can access c. Thread_1 s update will not be lost here Synchronized block public void increment() { synchronized(this){ c = c + 1; Unsynchronized threads operation sequences are not affected have to happen either before or after the synchronized operations take place NetProg 6 19

20 Deadlocks If two threads want to access the same resources, deadlock can occur. E.g. Thread 1 has got hold of B and wants to access A, while Thread 2 has got A and wants to access B. Deadlocks can occur intermittently, even between the same threads usually depend on timing can be hard to detect Wants to access A T1 Synchronized on B A B Synchronized on A T2 Wants to access B NetProg 6 20

21 Using Synchronization Synchronization and locks Synchronizing a method locks the method Static methods lock the class Synchronizing a block needs an object to lock It can be an arbitrary object not used for anything else E.g. synchronized(this){ Synchronization should be used sparingly It reduces performance It can result in a deadlock Synchronize only at the lowest level and only the code that really needs it To ensure that all threads see the most up-to-date values, the reading and writing threads must synchronize on a common lock 21

22 Secure Sharing of Objects Thread Confinement (no sharing) Ad-hoc approach: leaves it to the implementation Thread-local usage: all variables can be accessed through local variables ThreadLocal : Each thread has its own, independently initialized copy of the variable. They are typically private static fields Safe publication (sharing) Synchronized access in both the publishing and the consuming thread Reference to the object and the object s state must be made visible to other threads at the same time 22

23 Image source: Thread Scheduling (1) Priorities A thread with higher priority gets preference when executed A thread s initial priority is the same as that of its creator thread public static final int MIN_PRIORITY public static final int NORM_PRIORITY public static final int MAX_PRIORITY Interpretation of thread priorities varies between systems Thread priority may not indicate share of CPU NetProg 6 23

24 Thread Scheduling (2) Preemption A running lower priority thread can be interrupted when a higher priority thread wants to run Starvation A thread does not get (enough) CPU time Operating systems usually manipulate thread priorities to avoid starvation Changing priorities from the application It is a hint to the system The effect is hard to predict (it depends on the whole system - OS knows best ) NetProg 6 24 Image source:

25 Giving up Control Blocking Waiting for in I/O operation to complete Executing a synchronized block yield() Indicates to the JVM that another thread can run The JVM may ignore this hint The call has minimal effect if no need to yield wait(long timeout) Waits up to timeout or until another thread sends a notify() signal Keeps all its resources (others have to wait for those resources) sleep(long millisec) Forces the thread to pause, regardless of any threads waiting or not The sleeping time may be longer, if the JVM is busy doing other things shorter if an event or another thread wakes it up (e.g. by sending an interrupt) The thread still keeps all its resources Avoid using it in a synchronized block can cause a deadlock or long wait to wait for an event in another thread lazy solution, use wait() and notify() instead NetProg 6 25

26 Stopping a Thread Once a thread has started, nothing can (safely) stop it, except the thread itself. At most, the thread can be asked to stop itself (by getting interrupted). An interrupted thread may not immediately stop what it is doing. Threads may even ignore an interruption request (but that may compromise responsiveness). Stopping a thread is a two-step procedure Design the thread to act on interruption Interrupt the thread. It means sending a stop signal to the thread interrupt() interrupt this thread isinterrupted() tests if this thread has been interrupted join() waits for this thread to die NetProg 6 26

27 Interrupting a Thread Cooperative mechanism A signal is delivered to the thread The thread stops at the next available opportunity A thread can check for interruption regularly The isinterrupted() method will return true if interrupted (it leaves the interrupted status unchanged) If the thread is in a blocking method, it may take time until it can perform the check Blocking methods that support interruption usually throw an exception (InterruptedException) NetProg 6 27

28 Interruption Code Excerpt (1) Thread to be stopped public class mytask extends Thread{ public void run() { // Do something here if (isinterrupted()) { // Testing if the thread has been interrupted // The interrupted status of the thread is unaffected System.out.printf("Interrupted"); return; // Continue normally Main class public class Main { public static void main(string[] args) { Thread task=new mytask(); task.start(); Thread.sleep(5000); // Do something here task.interrupt();... 28

29 Interruption Code Excerpt (2) Propagating interruption Thread to be stopped public class mytask extends Thread{ public void run() { try{subtask(); catch (InterruptedException e) { System.out.printf("Interrupted, Thread.currentThread().getName()); return; // Continue normally... private void subtask() throws InterruptedException { // Do something here if (Thread.interrupted()) { // Testing if the thread has been interrupted // The interrupted status of the thread is cleared throw new InterruptedException();... Main class Same as on the previous slide 29

30 Finishing a Thread Method 1: join(long milliseconds) The invoking thread blocks and waits for another thread (whose method is invoked) to finish Can be used for getting the results from another thread It is a final method (you cannot override it) Method 2: Return from the run() method Often used in networking applications NetProg 6 30

31 Code Excerpt public class Main { public static void main(string[] args) { Thread thread1 = new Thread(myType1, Type 1"); Thread thread2 = new Thread(myType2, Type 2"); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); catch (InterruptedException e) { e.printstacktrace();... 31

32 Reentrancy Reentrant code: can be interrupted in the middle of execution and safely re-entered before the previous invocation completes Similar to thread safety, but not the same Reentrant code can achieve thread safety (by observing the respective rules) Thread safe code is not necessarily reentrant They still use similar (but not the same) tools (e.g. locks) Rules Reentrant code may not use any static or global non-constant data call non-reentrant programs, methods modify itself Examples for reentrant code Any recursive function Interrupt handling NetProg 6 32

33 Thread Groups Connect several threads together Can be used for handling multiple threads jointly You can list active group members (enumerate() list()) set limits for them (setmaxpriority()) Some methods are similar to Thread methods, (e.g. interrupt() setdaemon()) but many are missing (e.g. start() sleep()) Normally, a thread is in the same group as the main thread of the application Example: use in communication applications You want to stop input and output communication simultaneously NetProg 6 33

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

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

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

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

Threads Questions Important Questions

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

What is a thread anyway?

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

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

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi

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

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

Unit 4. Thread class & Runnable Interface. Inter Thread Communication Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more

More information

Concurrent Programming using Threads

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

CMSC 330: Organization of Programming Languages

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

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.

More information

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Unit - IV Multi-Threading

Unit - IV Multi-Threading Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first

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

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

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

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

Advanced Programming Concurrency

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

Multithreaded Programming

Multithreaded Programming core programming Multithreaded Programming 1 2001-2003 Marty Hall, Larry Brown http:// 2 Multithreaded Programming Agenda Why threads? Approaches for starting threads Separate class approach Callback approach

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

Threads in Java (Deitel & Deitel)

Threads in Java (Deitel & Deitel) Threads in Java (Deitel & Deitel) OOutline 1 Introduction 1 Class Thread: An Overview of the Thread Methods 1 Thread States: Life Cycle of a Thread 1 Thread Priorities and Thread Scheduling 1 Thread Synchronization

More information

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

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

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

Virtual Machine Design

Virtual Machine Design Virtual Machine Design Lecture 4: Multithreading and Synchronization Antero Taivalsaari September 2003 Session #2026: J2MEPlatform, Connected Limited Device Configuration (CLDC) Lecture Goals Give an overview

More information

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

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

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

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

Advanced Concepts of Programming

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

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

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

Object Oriented Programming (II-Year CSE II-Sem-R09)

Object Oriented Programming (II-Year CSE II-Sem-R09) (II-Year CSE II-Sem-R09) Unit-VI Prepared By: A.SHARATH KUMAR M.Tech Asst. Professor JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, HYDERABAD. (Kukatpally, Hyderabad) Multithreading A thread is a single sequential

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

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

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

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

Performance Throughput Utilization of system resources

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

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

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

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

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

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

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

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

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 Contents G53SRP: Java Threads Chris Greenhalgh School of Computer Science 1 Definition Motivations Threads Java threads Example embedded process Java Thread API & issues Exercises Book: Wellings 1.1 &

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

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

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci v1.0 20130323 Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci [module lab 2.1] CONCURRENT PROGRAMMING IN JAVA: INTRODUCTION 1 CONCURRENT

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The 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 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

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

By: Abhishek Khare (SVIM - INDORE M.P)

By: Abhishek Khare (SVIM - INDORE M.P) By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying

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

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

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

Threads, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

More information

Basics of. Multithreading in Java

Basics of. Multithreading in Java Basics of programming 3 Multithreading in Java Thread basics Motivation in most cases sequential (single threaded) applications are not adequate it s easier to decompose tasks into separate instruction

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Java implementations of concurrency process and threads

More information

Techniques of Java Programming: Concurrent Programming in Java

Techniques of Java Programming: Concurrent Programming in Java Techniques of Java Programming: Concurrent Programming in Java Manuel Oriol May 11, 2006 1 Introduction Threads are one of the fundamental structures in Java. They are used in a lot of applications as

More information

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

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University Threads & Timers CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 Multi-tasking When you re working, how many different applications do you have open at one

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

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

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

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

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

Chapter 32 Multithreading and Parallel Programming

Chapter 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 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

COMP 322: Fundamentals of Parallel Programming

COMP 322: Fundamentals of Parallel Programming COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 28: Java Threads (contd), synchronized statement Vivek Sarkar Department of Computer Science

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

Multithread Computing

Multithread 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 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

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

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

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

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

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004 Producing Production Quality Software Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004 Topics Models of concurrency Concurrency in Java 2 Why Use Concurrency? Enable

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

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

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

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal Java Threads What is a Thread? Individual and separate unit of execution that is part of a process multiple threads can work together to accomplish a common goal Video Game example one thread for graphics

More information

EDA095 Processes and Threads

EDA095 Processes and Threads EDA095 Processes and Threads Pierre Nugues Lund University http://cs.lth.se/pierre_nugues/ April 1st, 2015 Pierre Nugues EDA095 Processes and Threads April 1st, 2015 1 / 65 Time-Sharing Operating Systems

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

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2016 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

Lecture 17: Sharing Objects in Java

Lecture 17: Sharing Objects in Java COMP 150-CCP Concurrent Programming Lecture 17: Sharing Objects in Java Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming March 25, 2008 Reference The content of this lecture is based on

More information

MULTI-THREADING

MULTI-THREADING MULTI-THREADING KEY OBJECTIVES After completing this chapter readers will be able to understand what multi-threaded programs are learn how to write multi-threaded programs learn how to interrupt, suspend

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

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

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

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

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

CS360 Lecture 12 Multithreading

CS360 Lecture 12 Multithreading CS360 Lecture 12 Multithreading Thursday, March 11, 2004 Reading Multithreading: Chapter 16 Thread States At any time, a thread can be in one of several thread states: - Born: this is the time when the

More information

http://www.ugrad.cs.ubc.ca/~cs219/coursenotes/threads/intro.html http://download.oracle.com/docs/cd/e17409_01/javase/tutorial/essential/concurrency/index.html start() run() class SumThread extends

More information

Amity School of Engineering

Amity School of Engineering Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple

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

Concurrency. Fundamentals of Computer Science

Concurrency.  Fundamentals of Computer Science Concurrency http://csunplugged.org/routing-and-deadlock Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually

More information

EDAF65 Processes and Threads

EDAF65 Processes and Threads EDAF65 Processes and Threads Per Andersson Lund University http://cs.lth.se/per_andersson/ January 24, 2018 Per Andersson EDAF65 Processes and Threads January 24, 2018 1 / 65 Time-Sharing Operating Systems

More information

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

Concurrency in Java Prof. Stephen A. Edwards

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

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 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

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004 Thread Programming Comp-303 : Programming Techniques Lecture 11 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 11 Comp 303 : Programming Techniques Page 1 Announcements

More information