What is a thread anyway?

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

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

Concurrent Programming Benoît Garbinato

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

Java Threads. Introduction to Java Threads

Basics of. Multithreading in Java

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

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

Threads, Concurrency, and Parallelism

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

Threads Questions Important Questions

CS 351 Design of Large Programs Threads and Concurrency

THREADS & CONCURRENCY

Threads Chate Patanothai

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

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

Concurrent Programming using Threads

THREADS AND CONCURRENCY

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Object Oriented Programming. Week 10 Part 1 Threads

CST242 Concurrency Page 1

Java Threads. COMP 585 Noteset #2 1

THREADS & CONCURRENCY

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

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

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

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

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

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

EMBEDDED SYSTEMS PROGRAMMING More About Languages

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

Multi-threading in Java. Jeff HUANG

Techniques of Java Programming: Concurrent Programming in Java

Multithreaded Programming

Faculty of Computers & Information Computer Science Department

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

-Aditya Bhave CSCI-5448 Graduate Presentation

Threads & Concurrency

Multithreaded Programming

Threads & Concurrency

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

Synchronization in Java

Programming in Parallel COMP755

The New Java Technology Memory Model

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

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

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

Performance Throughput Utilization of system resources

CMSC 330: Organization of Programming Languages

Programming Language Concepts: Lecture 11

7. MULTITHREDED PROGRAMMING

Synchronization

CS 556 Distributed Systems

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

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

The Java Memory Model

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

Overview of Java Threads (Part 2)

Problems with Concurrency. February 19, 2014

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

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

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

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

Chapter 32 Multithreading and Parallel Programming

Multi-threaded programming in Java

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

Concurrent, Real-Time and Distributed Programming in Java

Component-Based Software Engineering

User Space Multithreading. Computer Science, University of Warwick

public class Shared0 { private static int x = 0, y = 0;

Multithread Computing

Unit - IV Multi-Threading

Dr.-Ing. Michael Eichberg

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Synchronization in Concurrent Programming. Amit Gupta

A6 AND A START ON THREADS AND CONCURRENCY

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

Java Monitor Objects: Synchronization (Part 1)

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Exercises and Labs. Part I. Exercises

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Concurrent Programming Lecture 10

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

CS 159: Parallel Processing

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Lecture 8: September 30

Module - 4 Multi-Threaded Programming

Writing Parallel Programs COMP360

Concurrent Programming

Animation Part 2: MoveableShape interface & Multithreading

Threads in Java (Deitel & Deitel)

1 Shyam sir JAVA Notes

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

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

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS180 Review. Recitation Week 15

Synchronization Possibilities and Features in Java

Transcription:

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 and share resources 1 1. "process" in the operating system sense 2

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 They can execute concurrently and share resources Discussion In Java, who is the scheduler? Who is the process? What are the resources? 3

Threads in Java In Java, threads are objects with (among other things) priority identifier state lock stack run() higher priority executed in preference of lower unique and does not change Thread.State enumeration: {NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED} unique unique a method that takes no args and returns void 4

Creating threads There are two ways and we will see both: 1. Extending the Thread class 2. Implementing the Runnable interface 5

1. Extending the Thread class Thread is a class in java.lang It has a run() method A class can be made into a thread by extending Thread and implementing run() 6

1. Extending the Thread class Example class PrimeThread extends Thread { long minprime; PrimeThread(long minprime) { this.minprime = minprime; } } public void run() { // compute primes larger than minprime } Create and run the thread: PrimeThread p = new PrimeThread(143); p.start(); 7

2. Implementing the Runnable interface Runnable is an interface in java.lang It has a single method run() A class can be made into a thread by implementing Runnable, i.e. implementing run(), and passing an instance of the class to a Thread constructor. 8

2. Implementing the Runnable interface Example class PrimeRun implements Runnable { long minprime; PrimeRun(long minprime) { this.minprime = minprime; } } public void run() { // compute primes larger than minprime } Create and run the thread: PrimeRun p = new PrimeRun(143); new Thread(p).start(); 9

Advantage of implementing Runnable over extending Thread Since Java has single inheritance, a class can't inherit from Thread and from another class at the same time. Implementing Runnable allows you to get a class with thread line behavior and inherit from a super class at the same time. 10

Abstract classes Vs Interfaces In Java, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces. If Java allowed for multiple inheritance, the distinction between Abstract class and Interface would be more blurred. 11

Some side tracking... Interface A group of related methods with empty bodies. A class can implement an interface give source code to all interface methods Discussion Both class and interface form a contract with the outside world. How are these contracts different? 12

More side tracking... Abstract class A class with empty methods that are declared abstract. An abstract class cannot be instantiated. An abstract class can be extended (i.e. subclassed) Subclass remains abstract until all abstract methods are overridden, i.e., given a concrete implementation. Discussion How is an abstract class similar to an interface? How are they different? 13

More side tracking... They are implemented in java.lang package java.lang exists since JDK 1.0 and is imported by default still, threads are not part of the language proper Discussion Threads in java.lang as opposed to in the "language proper" was a design decision by James Gosling et al. What are the advantages and disadvantage of this decision? 14

The Thread class public class Thread extends Object implements Runnable static currentthread() returns current running thread getid() getstate() can be one of {NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED} interrupt() join() waits for this thread to die sleep() start() yield() useful for implementing co routines 15

Synchronization Two basic synchronization idioms in Java: 1. Synchronized method 2. Synchronized statement/block 16

1. Synchronized method Used to enforce two things: 1. Mutual exclusion Prevent interleaving of two invocations of synchronized methods on the same object. 2. Ordering & visibility "When a synchronized method exits, it establishes a happens before relationship with any subsequent invocation of a synchronized method for the same object." 17

Synchronized statement/block We can synchronize only parts of a method as opposed to the whole method. public void add(int value){... synchronized(this){ this.count += value; }... } 18

java.util.concurrent Package with threading utilities, for example: Concurrent collections Atomic variables Synchronizers Locks Timing Frees the programmer from creating these utilities by hand 19

Object as Monitor The Object class has a unique lock, which we can use as a condition variable a wait() method notify() and notifyall() methods That looks a lot like a monitor... 20

Object as Monitor The Object class has a unique lock, which we can use as a condition variable limited to one condition variable a wait() method notify() and notifyall() methods That looks a lot like a monitor... 21

Object as Monitor The Object class has a unique lock, which we can use as a condition variable limited to one condition variable a wait() method ordering of wait queue is implementation dependent notify() and notifyall() methods That looks a lot like a monitor... 22

Object as Monitor The Object class has a unique lock, which we can use as a condition variable limited to one condition variable a wait() method ordering of wait queue is implementation dependent notify() and notifyall() methods signaling discipline is fixed at Signal & Continue That looks a lot like a monitor... 23

Object as Monitor The Object class has a unique lock, which we can use as a condition variable limited to one condition variable a wait() method ordering of wait queue is implementation dependent notify() and notifyall() methods signaling discipline is fixed at Signal & Continue That looks a lot like a monitor... a very simple one. 24

Semaphore implementation in Java public class Semaphore { private int value; public Semaphore( int initial ) { value = initial; } synchronized public void up() { ++value; notifyall(); } } synchronized public void down() throws InterruptedException { while (value == 0) wait(); --value(); } 25

Other interesting stuff... Weak memory models What's a memory model anyway? We will touch on that in a future class, but not relate it back to Java too much. Java's memory model is complex and a hot topic of debate. 26

Other interesting stuff... Albeit not covered by this class volatile keyword Lock class thread groups thread as daemon Remote Method Invocation (RMI) an object in a Java Virtual Machine invoking methods on object in another JVM falls into a Distribution vs Concurrency discussion 27

Last but not least, Please also look at main7java.pdf from the course website There you'll find more examples. 28

[Thread] https://en.wikipedia.org/wiki/thread_(computing) [Java thread] https://docs.oracle.com/javase/7/docs/api/java/lang/thread.html [Java concurrent] https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/packa ge summary.html 29