Techniques of Java Programming: Concurrent Programming in Java

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

Basics of. Multithreading in Java

Unit - IV Multi-Threading

EDAF65 Processes and Threads

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

EDA095 Processes and Threads

Concurrent Programming using Threads

CS 556 Distributed Systems

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

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

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

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

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

EDA095 Processes and Threads

What is a thread anyway?

7. MULTITHREDED PROGRAMMING

Multithreaded Programming

Time-Sharing Operating Systems. EDA095 Processes and Threads. Process Creation. The Content of a Process

Threads Chate Patanothai

Multithread Computing

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

Module - 4 Multi-Threaded Programming

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

Multi-threading in Java. Jeff HUANG

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

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

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

Threads Questions Important Questions

CS 351 Design of Large Programs Threads and Concurrency

Unit III Rupali Sherekar 2017

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

Software Practice 1 - Multithreading

Object Oriented Programming. Week 10 Part 1 Threads

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


Threads and Parallelism in Java

Java Threads. Introduction to Java Threads

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

Java Threads. COMP 585 Noteset #2 1

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Multi-Threaded Concurrency in Java

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Advanced Programming Concurrency

MVP1: Introduction to concurrency in JAVA

Programming Java. Multithreaded Programming

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

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Multiple Inheritance. Computer object can be viewed as

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

Robotics and Autonomous Systems

Synchronized Methods of Old Versions of Java

Java Basics 5 - Sockets. Manuel Oriol - May 4th, 2006

Programming Language Concepts: Lecture 11

THREADS AND MULTITASKING ROBOTS

ROBOTICS AND AUTONOMOUS SYSTEMS

CS 159: Parallel Processing

Threads in Java. Threads (part 2) 1/18

Figure 6.1 System layers

Dr.-Ing. Michael Eichberg

Multithreaded Programming

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

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

CMSC 330: Organization of Programming Languages

Introduction to Java Threads

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

Synchronization in Concurrent Programming. Amit Gupta

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

Component-Based Software Engineering

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

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Parallel Programming Practice

Advanced Concepts of Programming

Object-Oriented Programming Concepts-15CS45

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

Programming in Parallel COMP755

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

CS180 Review. Recitation Week 15

CS18000: Programming I

Chapter 32 Multithreading and Parallel Programming

Overview of Java Threads (Part 2)

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

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

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

Unit 5 - Exception Handling & Multithreaded

Parallel Programming Practice

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

MULTI-THREADING

JThreads/C++ Version 2.0.0b1. IONA Technologies PLC

UNIT V CONCURRENT PROGRAMMING

Synchronization

Faculty of Computers & Information Computer Science Department

Principles of Software Construction: Concurrency, Part 2

Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub

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

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

CS342: Software Design. November 21, 2017

EMBEDDED SYSTEMS PROGRAMMING More About Languages

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

Threads. What Is a Thread? Customizing a Thread's run Method. Understanding Threads. Subclassing Thread and Overriding run. Thread Objects.

Transcription:

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 their use is meant to be simple. In practice, very few is required from programmer s perspective. It is only needed to simply specialize a class or define a method to benefit from the Thread facility. When considering concurrent programs, there is a need to synchronize. As an introduction, let precise that each object has a lock that can be used to synchronize threads. The final methods wait, notify and notifyall are all manipulating this lock as well as synchronized methods and blocks. Section 2 presents threads and runnable objects. Section 5 explains how lowlevel mechanisms work. Section 4 presents synchronized blocks and methods. Section 3 presents volatile variables. 2 Threads, Runnables and ThreadGroup 2.1 Threads and Runnable The class Thread is the primary class for defining threads. By calling the start() method on a thread, programmers create a new thread that executes the run() method. Once the thread has been launched, the start() method returns. Note that thread can only be started once. In particular, they cannot be restarted even if they finished execution. The simplest way to create a new Thread is thus to subclass the class Thread and override the method run() and include the code that one wants to execute. As shown in Table 1 Instances of the class Thread can also be created by providing instances of classes that implement interface Runnable. The interface itself only rquires to have the run() method to be implemented. As an example, it is possible to create a new thread using an object o that is an instance of a class implementing Runnable: Runnable o;... (new Thread(Runnable)).start(); 1

Table 1: Thread Methods java.util.thread Thread() Creates a new thread. Thread(Runnable target) New thread with code of the argument. Thread(Runnable target, New thread with a name and custom String name) code. Thread(String name) New thread with a name. Thread(ThreadGroup group, Creates a new thread and adds it to Runnable target) a specific ThreadGroup. Thread(ThreadGroup group, Creates a new thread with a given name Runnable target, String name) and adds it to a specific ThreadGroup. Thread(ThreadGroup group, Creates a new thread with a given name Runnable target, String name, and adds it to a specific ThreadGroup. long stacksize) The stack size is indicative. Thread(ThreadGroup group, Creates a new thread with a given name String name) and adds it to a specific ThreadGroup. static Thread currentthread() String getname() Thread.state getstate() int getpriority() ThreadGroup getthreadgroup() void interrupt() static boolean interrupted() void join() void join(long millis) void run() static void setdefault- UncaughtExceptionHandler( Thread.UncaughtException- Handler eh) static void sleep(long millis) void start() Returns a reference on current thread. Returns this thread name Returns this thread state (interrupted...) Returns this thread priority Returns this thread s group Interupts the thread. Checks if the current thread has been interrupted. Waits for the thread to end Waits at most millis milliseconds for this thread to end. method called upon thread starting. Changes the exception handler for this thread. Stops the current thread for millis milliseconds. Starts a new thread. 2.2 ThreadGroup Threads are grouped in ThreadGroups. ThreadGroups are hierarchical: each one can contain one or more other ThreadGroups. Each ThreadGroup is an execution domain that contains the threads. In particular, a thread belonging to a ThreadGroup can only modify/ask information about its ThreadGroup s threads or the threads of the children of its ThreadGroup (and recursively). By default, it is not possible to interrupt threads from another ThreadGroup. It is possible to override this feature by setting up different policies through the SecurityManager. 2

2.3 Interrupting a Thread What is argued in the APIs is that the methods destroy(), stop(), suspend() and resume() are deprecated meaning that they should be avoided if possible and that they may be removed at any time when the language evolves. Table 2: Thread Deprecated Methods java.util.thread void destroy() Not implemented. Returns an exception. void resume() Resumes execution of a suspended thread. void stop() Stops the execution. Locks are released. void stop(throwable obj) Stops the thread and raise the throwable. void suspend() Suspends the thread The solution offered 1 states that calls to stop() and suspend() should be avoided to use interrupt(). The method itself only sets a flag returned by interrupted() to true and visits the interruptible operations (visit APIs 2 for more details). In practice even if the deprecated methods are unsafe, they are the only real way to interrupting threads and they are implemented(with the notable exception of destroy). The only precaution to take when using them, is to ensure that locks are released or threads are not interrupted while others need to release locks. 3 volatile variables volatile variables are variables on which operations are executed in an atomic manner. It is also stated in the Java 5.0 specifications that operations on volatile variables respect sequential consistency: programmers can be sure that they execute in the same order as they were specified (or at least it is not possible to observe a behavior that would be invalidate with respect to that assumption); 4 synchronized blocks/methods To synchronize blocks of instructions, the best way is to use the synchronized keyword. This keyword can be applied to both a block of code and to a method body. In any case, if the lock to be taken is already taken, the code blocks until the lock is released. When the lock is released, there is a competition between all waiters and only one can grab the lock. When applied to a method body, the method invocation is taking the lock on the object on which the method is applied. If the method is a class method 1 http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadprimitivedeprecation.html 2 http://java.sun.com/j2se/1.5.0/docs/api/java/lang/thread.html#interrupt() 3

(static) the lock is taken on the class object. As an example, a synchronized method can be declared as follows: synchronized void inccount(){ Another way of taking synchronization locks is to use the synchronized keyword on an object to take its lock. The block following the keyword is then having the lock. As an example, an equivalent form of the preceeding example is: void inccount(){ synchronized(this){ 5 wait and notify As it is often needed to synchronize multiple threads at the same time, there are other constructs that allow synchronization. In particular, while in a synchronized block, it is possible to release a lock and wait for a notification to wake-up and try to grab the lock. This is typically realized through the use of the wait() method. In order to wake up processes waiting on a given lock, it is needed to use notify() or notifyall() to respectively wake up one waiting thread or all waiting threads. This can also be done only within a block that has the lock on the considered object. When woken up, threads try to grab the lock on which they have been notified and block until they grab it. As a example let consider two threads that perform a ping-pong sequence: public class ThreadExample2 { private static class MyThread extends Thread{ boolean isping; Object lock; private MyThread(Object lock, boolean isping){ this.lock=lock; this.isping=isping; public void pingpong()throws Exception{ synchronized(lock){ while(true){ if (isping) System.out.println("Ping"); else System.out.println("Pong"); lock.notifyall(); lock.wait(); 4

public void run() { try{ pingpong(); catch (Exception e){ public static void main(string[] args) { Object o=new Object(); (new MyThread(o,true)).start(); (new MyThread(o,false)).start(); 6 Exercises 1. Is the following program going to terminate? public class ThreadExample { private static class MyThread extends Thread{ private static int count; private static volatile int count2; private static int count3; Object lock; private MyThread(Object lock){ this.lock=lock; public void run(){ synchronized(lock){ lock.notifyall(); count++; try { lock.wait(); catch (Exception e){ synchronized static void inccount(){ public static void main(string[] args){ Object o=new Object(); for (int i=0; i<10;i++) (new MyThread(o)).start(); 2. Is it possible that the following program have the given trace? 5

public class ThreadExample { private static class MyThread extends Thread{ private static int count; private static volatile int count2; private static int count3; Object lock; private MyThread(Object lock){ this.lock=lock; public void run(){ synchronized(lock){ count++; count2++; inccount(); System.out.println("count="+count+" count2="+ count2+" count3="+count3); synchronized static void inccount(){ public static void main(string[] args){ Object o=new Object(); for (int i=0; i<10;i++) (new MyThread(o)).start(); Trace: count=3 count2=4 count3=4 count=4 count2=4 count3=4 count=8 count2=8 count3=8 count=9 count2=9 count3=9 count=5 count2=5 count3=5 count=10 count2=10 count3=10 count=7 count2=7 count3=7 count=8 count2=8 count3=8 count=6 count2=6 count3=6 count=9 count2=9 count3=9 3. A thread pool is a group of threads that can be used to program a server program without creating new threads each time a new connection is created but rather reuse existing ones. How would you program a thread pool? 6