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

Similar documents
7. MULTITHREDED PROGRAMMING

Threads in Java (Deitel & Deitel)

Performance Throughput Utilization of system resources

CS360 Lecture 10 Multithreading

15CS45 : OBJECT ORIENTED CONCEPTS

Threads Questions Important Questions

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Multithread Computing

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

Object Oriented Programming. Week 10 Part 1 Threads

Pre- and post- CS protocols. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7. Other requirements for a mutual exclusion algorithm

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

CS360 Lecture 12 Multithreading

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

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

Java Threads. COMP 585 Noteset #2 1

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Synchronization

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

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

Multithreading in Java Part 2 Thread - States JAVA9S.com

Chapter 32 Multithreading and Parallel Programming

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Unit III Rupali Sherekar 2017

Multithreaded Programming

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

Advanced Concepts of Programming

Concurrent Programming using Threads

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

Compaq Interview Questions And Answers

Concurrent Programming

THREADS AND CONCURRENCY

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

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

G52CON: Concepts of Concurrency

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

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

Threads Chate Patanothai

Unit - IV Multi-Threading

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

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Multithreaded Programming

CS 231 Data Structures and Algorithms, Fall 2016

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

PESIT Bangalore South Campus

Introduction to Programming Using Java (98-388)

Multi-threading in Java. Jeff HUANG

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

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

THREADS & CONCURRENCY

Chapter 19 Multithreading

EMBEDDED SYSTEMS PROGRAMMING More About Languages

Amity School of Engineering

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

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

CIS233J Java Programming II. Threads

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

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

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

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

Points To Remember for SCJP

What is a thread anyway?

Threads. Still Chapter 2 (Based on Silberchatz s text and Nachos Roadmap.) 3/9/2003 B.Ramamurthy 1

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

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

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

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

Concurrency in Java Prof. Stephen A. Edwards

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

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

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

Module - 4 Multi-Threaded Programming

Threads, Concurrency, and Parallelism

Concurrent Computing CSCI 201 Principles of Software Development

Threads & Concurrency

CSCD 330 Network Programming

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

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Animation Part 2: MoveableShape interface & Multithreading

Programming. Syntax and Semantics

Dealing with Issues for Interprocess Communication

Java Programming. Price $ (inc GST)

Processes and Threads

Reintroduction to Concurrency

CSCD 330 Network Programming

Outline. Threads. Single and Multithreaded Processes. Benefits of Threads. Eike Ritter 1. Modified: October 16, 2012

Lecture 7 Java SE Multithreading

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall()

1 OBJECT-ORIENTED PROGRAMMING 1

Figure 6.1 System layers

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

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency

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

Special Topics: Programming Languages

Transcription:

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 these notes for their own use. page 1 Quiz on Tuesday April 13 30 minutes or less. Write a simple Java program with computation and i/o (no threads). You should be able to do any kind of simple program you could write in Programming II or Data Structures in C++, but in Java. Be able to state information and answer simple questions about Java compilation, classpaths, packages. If you did the first example assignment easily, there should be no problems if you can express page 2 what you know Things to try in Java Write a program that uses inheritance, interfaces, Vectors, file I/O, packages. Study AWT and Java Swing to find out how to use the Java class libraries for GUI construction. Our Java programming won t need it, however. Java facts and questions How do you handle global variables in Java? Java has automatic garbage collection -- do new() to allocate, but never need to do delete. What implications does automatic gc have for programming? page 3 page 4 Forcing a deallocation of storage int big_array[100000]; Another Java fact and question How do you do a linked list in Java? // now we don t want to use the storage anymore big_array = null; // garbage collector // automatically deallocates storage from the // heap. page 5 page 6

Java procedures are mainly call by reference This means that procedures can easily alter objects passed to them as parameters. Building your own exceptions. Class BrucesArgumentNegativeException extends Exception{; page 7 page 8 Programming with exceptions. class Factorial{ Public static int compute(int k) throws BrucesArgumentNegativeException, other exceptions { if (k<0) throw new BrucesArgumentNegativeException(); else return 1; (and later in a program). try { System.out.println ( answer is: + Factorial.compute(n)); catch(brucesargumentnegativeexception e) { System.err.println(e + oops ); continue; ;. Java lacks some C++ features No templates. But superclass is Object. Could program a stack class with Objects, and then cast into an object of another class. Exception: primitive data types such as int, float are not subclasses of Object. However, there are wrapper classes Integer, Double, etc. No overloading of operators (although function overloading is okay). No i/o operators <<, >>. No general multiple inheritance. page 9 page 10 No environment variables in Java (not system independent) No such thing as environment variables as there are with C/C++ and Unix because this is not OS independent. There s a system property setting mechanism that accesses properties declared in the command line invocation called System.getProperty() read about it in the Java documentation. What does final mean? public final class FinalCircle extends GraphicCircle { When a class is declared with the final modifier, it means that it cannot be extended. It s a way of declaring constants for a class: final int BUFFERSIZE = 10; page 11 page 12

page 13 Java threads Use the built-in Thread class in Java. You need to supply the programming that the thread will follow in order to do multi-threaded programming. There are two ways to get a new thread in Java Extend (subclass) the Thread class. Provide a run method in the subclass. Create a Thread object incorporating an object that specifies the Thread s run method. One way to get a thread: extend (subclass) the built-in Thread class In file AThread.java: class AThread extends Thread { public AThread(String name) {super(name); public void run() { System.out.println( My name is + getname()); In file test.java: class test { public static void main(string[] args) { AThread a = new AThread( mud ); // Thread name a.start(); page 14 page 15 Thread Construction Different Thread constructors accept combinations of arguments supplying: A Runnable object, in which case Thread.start invokes run of the supplied Runnable object A String that serves as an identifier. Not useful except for tracing and debugging ThreadGroup in which the new Thread should be placed An alternative: implement Runnable interface, use another form of the Thread constructor In file AClass.java: class AClass implements Runnable { public void run() { System.out.println( My name is + Thread.currentThread().getName()); In file test2.java: class test { public static void main(string[] args){ AClass aobject = new AClass(); // Use alternative constructor for Thread class Thread athread = new Thread(aObject, mud, too ); // Thread name athread.start(); page 16 Extend (inherit) Thread versus implement Runnable The implementing Runnable technique allows you to extend another class as well as getting threads. Since Java does not have full multiple inheritance, you can t do that with the first method. Starting threads Invoking its start method causes an instance of class Thread to initiate its run method A Thread terminates when its run method completes by either returning normally or throwing an unchecked exception Threads are not restartable, even after they terminate isalive returns true if a thread has been started by not has not terminated page 17 page 18

Thread States and Scheduling A Java thread can be in new, runnable, running, blocked, and dead states. The Threads class has methods that move the thread from one state to another. Thread states New state a Thread newly created. Runnable after being started, the Thread can be run. It is put into the run queue of Threads and waits its turn to run. Runnable does not mean running. Running the thread is executing its code. On a uniprocessor machine, at most one thread can run at a time. page 19 page 20 Thread/process states More thread states start yield stop sleep/suspend resume 0 1 stop/end 2 run 3 suspend 4 stop dispatch stop 1 terminated 2 running 3 suspended 4 - runnable page 21 Blocked the thread is waiting for something to happen It is waiting for an i/o operation it is executing to complete It has been told to sleep for a specified period of time through the sleep method It has executed the wait() method and will block until another thread executes a notify() or notifyall() method. It will return to runnable state after sleeping, notifying, etc. page 22 page 23 More thread states Terminated The final state. After reaching this state the Thread can no longer execute. A thread can reach this state after the run method is finished, or by something executing its stop() method. Threads can kill themselves, or a thread can kill another thread. page 24 The run queue of runnable threads The Java language specification does not specify how Java is supposed to choose the thread to run if there are several runnable threads of equal priority. One possibility pick a thread and run it until it completes, or until it executes a method that causes it to move into a non-running state. Another possibility time slicing : pick a thread and run it for a short period of time. Then, if it is not finished, suspend it and pick another thread to run for the same period of time.

page 25 The semantics of yield() public static void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute. Java Language Reference: In some cases, a large number of threads could be waiting on the currently running thread to finish executing before they can start executing. To make the thread scheduler switch from the current running thread to allow others to execute, call the yield() method on the current thread. In order for yield() to work, there must be at least one thread with an equal or higher priority than the current thread.. Java realities Most implementations of Java typically use time-slicing In older Java versions on Solaris the default was to use green threads, which meant that there was no time-slicing. (many-to-one thread model) Currently Solaris uses native threads (many-to-many thread model) page 26 Thread synchronization Thread synchronization, con t t.wait() blocks until t.notify() method is called. t.suspend() puts it into suspended state. t.resume() makes it runnable again. suspend and resume are deprecated methods, do not use. A deprecated method is one whose design has fallen out of favor and may be unsupported in page 27 page 28 future Java versions stop() is also a deprecated method, avoid its use in your programming. Most of the time you should let a thread finish by having it conclude executing its run() method. stop() causes an untidy conclusion to a thread, which may disrupt correct operation of other threads which may continue to run after the stopped thread. page 29 More Thread methods Thread.currentThread returns a reference to the current Thread Thread.sleep(long msecs) causes the current thread to suspend for at least msecs milliseconds Thread.interrupt is the preferred method for stopping a thread (not Thread.stop) page 30 Thread Priorities With multiple threads, one can assign priorities ( a number) to each thread, and run the ones with highest priority. t.setpriority(int). In some versions of Solaris multiple threads with the same priority have no time-slicing. The book provides a class library that implements time slicing on Solaris. You import it and then do new Scheduler(time slice amount); This course discusses techniques that avoid the use of priorities in establishing synchronization between threads.

page 31 Priorities Each Thread has a priority, between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY (from 1 to 10) Each new thread has the same priority as the thread that created it The initial thread associated with a main by default has priority Thread.NORM_PRIORITY (5) getpriority gets current Thread priority, setpriority sets priority Why you should not try to achieve correctness in concurrency problems using priorities A scheduler is generally biased to prefer running threads with higher priorities (depends on JVM implementation), but there is no iron-clad guarantee that a thread with a higher priority must run instead of that with a lower priority. There are only a small number of different priorities. If you have a problem with many threads you will run out of distinct priorities to assign threads. page 32 page 33 Concurrent programming goals Your job is to write a program that will work correctly regardless of whether there is timeslicing or not. The thread s programming should use synchronization methods such as semaphores or wait() and notify(); to make sure that a particular thread relinquishes execution if that is needed to for correct operation. Avoid stop(), suspend(), resume(), destroy(). Priorities often used as a crutch; the algorithm may not scale up to more threads if you have more threads than priority levels. page 34 Java debugging with multithreaded programs See what book has to say about it use print statements, mainly, and dump output of each thread into a separate file or at least with distinctive output. jdb is a Java debugger that allows you to start/stop individual threads. Hard to control concurrent execution of threads to reproduce a bug in a debugger. Race conditions What is a race condition? When two threads or processes sharing memory write and read simultaneously, with the effect that the work that one or the other is doing gets lost. Example N=N+1; in assembly this is load value of N into register R, ad one to register, store value of R back into memory location for N. Problems with N=N+1 race If two threads did this, we could end up with either N+2 or N+1 depending on whether their operations were interleaved or not. page 35 page 36

Other situations A husband and wife work in different places. At lunch they both go visit an ATM to withdraw money. If they withdraw simultaneously, what would a race condition do to their bank balance? page 37