Lecture 4 JAVA (46-935) Somesh Jha

Similar documents
Problems with Concurrency. February 19, 2014

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

Concurrent Programming using Threads

Multithreaded Programming

7. MULTITHREDED PROGRAMMING

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

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

Performance Throughput Utilization of system resources

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

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

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

CS 351 Design of Large Programs Threads and Concurrency

Java Threads. Thread. Rui Moreira. control within a program. threads. performed concurrently

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Threads and Parallelism in Java

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

Concurrency in Java Prof. Stephen A. Edwards

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

Advanced Concepts of Programming

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

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

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

CSCD 330 Network Programming

Multi-threading in Java. Jeff HUANG

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Definition: A thread is a single sequential flow of control within a program.

CSCD 330 Network Programming

CS360 Lecture 12 Multithreading

CPS221 Lecture: Threads

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Concurrency and Java Programming

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Multiple Inheritance. Computer object can be viewed as

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Faculty of Computers & Information Computer Science Department

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

What is a thread anyway?

An Exceptional Class. by Peter Lavin. June 1, 2004

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

F I N A L E X A M I N A T I O N

CSCE3193: Programming Paradigms

CMSC 330: Organization of Programming Languages

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

Threads in Java (Deitel & Deitel)

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

JAVA BASICS II. Example: FIFO

Programming Language Concepts: Lecture 11

What's wrong with Semaphores?

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

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

Object Oriented Programming. Week 10 Part 1 Threads

Stacks and Queues

CS180 Review. Recitation Week 15

Techniques of Java Programming: Concurrent Programming in Java

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

Stacks have many uses Arithmetic Language parsing Keeping track of recursion (more in this in a week or so)

Java Threads. Introduction to Java Threads

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

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

CmpSci 187: Programming with Data Structures Spring 2015

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

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

javagently jg3e H:\ ProgTwo Programming II Lecture 7 A case study (class containing an array) and model diagrams. 02/02/2003 Dr Andy Brooks 1

this keyword (1). this with constructor (2). cisc3120 design and implementation of software applications I spring 2015 lecture # I.

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

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

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

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

Stacks Goodrich, Tamassia

Threads, Concurrency, and Parallelism

Stacks and Queues III

Threads and Concurrency in Java

CS 556 Distributed Systems

Multithreading Pearson Education, Inc. All rights reserved.

1.00 Lecture 30. Sending information to a Java program

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

Unit - IV Multi-Threading

Principles of Software Construction: Concurrency, Part 2

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Lecture 10 State dependency

Sockets and RMI. CS151 Chris Pollett Dec. 5, 2005.

CSCD 330 Network Programming

Lecture 9: Introduction to Monitors

Data Structures G5029

Problems with Concurrency

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

COMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

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

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

SFDV3006 Concurrent Programming

FIFO PAGE REPLACEMENT : import java.io.*; public class FIFO {

ITI Introduction to Computing II

Transcription:

Lecture 4 JAVA (46-935) Somesh Jha 1

Inner Classes Flashback totheabstracttermstructure class. There was a SlowYieldVolObject which computed: { (i = 0) Dierence between computed yield and the market yield { (otherwise) Dierence between computed volatility and the market volatility. Clumsy! The object used by the NewtonRaphson solver belongs in the TermStructure class. Nobody else uses it. 2

Inner Classes (Contd) Put a YieldVolObject class inside the TermStructure class. Nobody else except TermStructure class can use the YieldVolObject. These are called member classes. There are other kind of inner classes. (Read Chapter 5). 3

Code Fragment /** Abstract class for building a BDT type interest-rate model. @author Somesh Jha */ package interestrate; import mathutil.*; public abstract class TermStructure { private static final boolean DEBUG=false; //time horizon int T; //Used by the Newton-Raphson solver YieldVolObject slowyieldvolobj; NewtonRaphson slowsolver; //parameters of the BDT model double r[]; double k[]; //bond yields and yield volatilities //at time 0 double yield[]; double volatilities[]; //nodes[i] points to link list of //nodes with time i LinkList nodes[]; 4

class YieldVolObject extends AbstractFunctionObject { //Yield and volatality are computed for the //bond of that maturity public int maturity; public YieldVolObject() { //call the constructor for the super class super(2); }//end of constructor //If i==0 calculate the yield and otherwise //calculate the vol. Use values as value //of r[t] and k[t] public double evaluate(int i, double val[]) { r[maturity-1]=val[0]; k[maturity-1]=val[1]; if (i==0) { double tempyield =slowyield(0,0,maturity); return(tempyield-yield[maturity-1]); } else { double tempvol = slowlogvol(0,0,maturity); return(tempvol-volatilities[maturity-1]); } }//end of evaluate }//end of YieldVolObject 5

Points to notice Notice that the class YieldVolObject is dened inside the TermStructure class. Notice that YieldVolObject has complete access to data of the TermStructure class. Nobody can access YieldVolObject from outside. 6

JAVA packages We have or will cover some classes from the following packages: { java.applet (Classes concerned with applets) { java.awt (Classes concerned with GUIs) { java.io (Classes concerned with I/O) { java.util (Classes concerned with various utilities) { java.net (Classes concerned with networking) Whole list of packages given on page 86-89 in the book. 7

JAVA I/O package We covered various kind of I/O streams. How to read and write to a le. Avery wide variety of I/O provided by JAVA. 8

JAVA utlities package StingTokenizer is in the java.util package. Allows us to break a line into tokens for parsing. Consider the following fragment of code. String line=''hhh:xxx:ccc''; StringTokenizer tokenizer = new StringTokenizer(line,'':''); String firsttoken = tokenizer.nexttoken(); String secondtoken = tokenizer.nexttoken(); 9

Other interesting classes HashTable Date Random Vector Stack Read about them on page 527. 10

java.lang package This package is loaded up by default. String, Math, System, Double are all in this package. Object and Exception are also dened in this package. Read about it on page 442. 11

What is a thread? A Thread is a like a program. Two threads run independently like separate programs. Dierence is that threads run within a program and hence can share variables. 12

Concurrent Programming Threads enable concurrent programming. Two separate tasks can be going on in parallel in a single program. Let us say you enter the Bloomberg website. 13

Concurrent Programming (contd) The following tasks can be going on in parallel: { Various indexes being displayed in a box. { Hot news ticker. { Asking the user to enter a stock symbol. All these separate tasks could be handled by separate threads. 14

A small example package threadrelated; public class MyThread extends Thread { public MyThread(String name) { super(name); }//end of MyThread public void run() { for(int i=0; i < 10; i++) { System.out.println(i+" "+getname()); try { sleep((int)math.random()*1000); } catch (InterruptedException e) {}; } System.out.println("DONE! "+getname()); }//end of run }//end of MyThread 15

Constructor A thread class extends the JAVA class Thread dened in the package java.lang. The constructor takes the name of thread as an argument. What does super(name) do? 16

run method Whenever a thread is started, run method is called. The run method in this case goes through the loop 10 times. sleep((int)math.random()*1000) suspends the thread for a random time. What is Math.random()? getname() gets the name of the thread. 17

Main Program package threadrelated; public class testmythread { static public void main(string argv[]) { MyThread thread1 = new MyThread("put"); MyThread thread2 = new MyThread("call"); thread1.start(); thread2.start(); } } 18

Main Program (Contd). There are two threads: thread1 and thread2. First thread has name put and the second one call. The start method on the thread starts the thread. 19

When does a thread stop? A thread stops when either of the following events happen: { run method exits. { stop method is called on the thread. 20

Output of the program 0 put 0 call 1 call 1 put 2 put 2 call 3 put 3 call 4 put 5 put 4 call 5 call 6 put 6 call 7 put 7 call 8 put 8 call 9 put 9 call DONE! put DONE! call 21

Synchronization Suppose that there are two threads T 1 and T 2 that share two variables i and j. Suppose each thread increments i and then increments j by the value of i. We can have two sample executions shown on the next slide. 22

Two executions Initial value i=1 j=1 First exceution i = i+1 (T1 executes) j = j+i (T2 executes) i = i+1 (T2 executes) j = j+i (T1 exceutes) Second execution i = i+1 (T1 executes) j = j+i (T1 executes) i = i+1 (T2 executes) j = j+i (T2 executes) 23

Inconsistency! First Exceution T 1 observes j =6. Second Exceution T 1 observes j =3. Need to control access to shared variables. Answer: Synchronization 24

Toy Trading System Each trader enters the transaction he/she just made. A producer thread reads the transaction record and puts in a queue. Consumer threads read records from the queue and log it. 25

Toy Trading Example (Fig) Trader log Consumer 1 Consumer 2 log Queue Producer Figure 1: A Toy Trading System 26

Producer Thread package threadrelated; import java.io.*; public class ProducerThread extends Thread { Queue myqueue; BufferedReader bsystemin; public ProducerThread(String name, Queue q) { super(name); myqueue = q; bsystemin = new BufferedReader(new InputStreamReader(System.in)); } public void run() { try { String line; while ((line = bsystemin.readline())!= null) { TraderEntry tentry = new TraderEntry(line); myqueue.add(tentry); }//end of while } catch (IOException e) { System.err.println("Exception occured "+e.getmessage()); } } }//end of run 27

Constructor Constructor takes: { Name of the thread. { The queue to put things in. 28

run method Reads a line from the screen. Makes that line into a trader-entry. Adds that trader-entry to the queue. 29

TraderEntry package threadrelated; import java.util.*; public class TraderEntry { //put, call,... String transactiontype; //price and amount double price, amount; static final int NO_OF_ENTRIES=5; String counterparty; String comments; public TraderEntry(String ttype, double p, double a, String cp, String co) { transactiontype = ttype; price = p; amount = a; counterparty = cp; comments = co; }//end of first constructor public TraderEntry(String line) { StringTokenizer tokenizer = new StringTokenizer(line); if (tokenizer.counttokens() == NO_OF_ENTRIES) { transactiontype = tokenizer.nexttoken(); price = Double.valueOf(tokenizer.nextToken()).doubleValue(); amount = Double.valueOf(tokenizer.nextToken()).doubleValue(); 30

counterparty = tokenizer.nexttoken(); comments = tokenizer.nexttoken(); } }//end of TraderEntry public String tostring() { StringBuffer result=new StringBuffer(transactionType); result = result.append(" : "); result = result.append(price); result = result.append(" : "); result = result.append(amount); result = result.append(" : "); result = result.append(counterparty); result = result.append(" : "); result = result.append(comments); return(result.tostring()); }//end of tostring() }//end of TraderEntry 31

Constructors First Constructor This constructor takes all ve arguments explicitly. Second Constructor Second constructor takes a string and parses the entries out of that. 32

tostring method Notice the use of StringBuffer in this method. This class represents a string of characters. A StringBuffer object grows as things are appended to it. 33

ConsumerThread package threadrelated; public class ConsumerThread extends Thread { Queue myqueue; public ConsumerThread(String name, Queue q) { super(name); myqueue = q; } public void run() { while(true) { TraderEntry tentry = (TraderEntry)myQueue.delete(); System.out.print("Consumer <"+getname()+"> "); System.out.println(tEntry); } } }//end of run 34

Constructor Same as the producer thread. 35

run method Goes on forever. Each time in the loop it gets an entry from the queue. Prints it out on the screen. What happens in the following statement? System.out.println(tEntry); 36

Main program package threadrelated; import java.io.*; public class testproducerconsumer { static public void main(string argv[]) { String line; Queue entryqueue = new Queue(1000); ProducerThread prod = new ProducerThread("producer",entryQueue); ConsumerThread consumer1 = new ConsumerThread("consume-1",entryQueue); ConsumerThread consumer2 = new ConsumerThread("consume-2",entryQueue); prod.start(); consumer1.start(); consumer2.start(); } }//end of main 37

Main program Has one producer thread prod. Has two consumer threads consumer1 and consumer2. Starts the three threads. 38

Queue shared Notice that the queue entryqueue is shared between the three threads. Need to synchronize access to the queue. Only one thread should be accessing the queue object at any time. 39

Queue is empty What if a consumer thread wants to get a trader-entry and the queue is empty? Consumer thread should go into a wait state. When a producer thread puts something in the queue, it should notify the waiting consumer thread. Analogous situation happens when the queue is full. 40

Queue class package threadrelated; public class Queue { int size; private Object data[]; int front, back; private boolean empty, full; public Queue(int size) { this.size = size; data = new Object[size]; front=back=0 ; empty=true; full=false; }//end of Queue private boolean isempty() { return(empty); } private boolean isfull() { return(full); } public synchronized void add(object obj) { while (isfull()) { try { wait(); } 41

catch (InterruptedException e) { } }//end of while boolean wasempty = isempty(); //queue has space data[front]=obj; if ((front+1)%size == back) full=true; front = (front+1)%size; empty=false; if (wasempty) notifyall(); }//end of add public synchronized Object delete() { while (isempty()) { try { wait(); } catch (InterruptedException e) { } }//end of while boolean wasfull = isfull(); Object obj=data[back]; if ((back+1)%size == front) empty=true; back = (back+1)%size; full=false; if (wasfull) notifyall(); return(obj); }//end of delete public synchronized String tostring() { String result=" "; 42

if (!isempty() ) { for(int i=back; i!= front; i=(i+1)%size) { result = result + data[i].tostring(); result= result+" \n"; } }//end of if return(result); }//end of tostring }//end of Queue 43

Queue class Implements a circular queue. Figure out the logic. The variable size holds the size of the queue. 44

delete method Deletes an object from the end of the queue and returns it. Notice the denition. public synchronized Object delete() This means that a thread has to acquire the unique lock associated with this object before it can execute the delete method. 45

delete method (Contd.) Suppose the consumer1 thread executes the delete method and acquires the lock. Now suppose the prod thread executes the add method. The thread prod blocks because the lock associated with the queue object is with the thread consumer1. 46

Waiting Suppose thread consumer2 executes the method delete to get a trader-entry. Suppose the queue is empty. Thread consumer2 puts itself in the wait state using the following fragment of code: while (isempty()) { try { wait(); } catch (InterruptedException e) { } }//end of while 47

Who wakes it up? Recall that consumer2 is waiting. When the producer thread prod puts stu in the queue and it was empty, it noties the waiting threads. The fragment of code that does this is: if (wasempty) notifyall(); 48

Client-Server Programming Server runs on a known host and a port. Has all the heavy-weight stu in it. { Databases with historical data. { Complicated functionality (pricing and PDE code). 49

Client Client is a light-weight program that uses the server. Generally, the client knows the host and the port to connect to the server. Sockets enable client-server programming in JAVA. 50

Client-Server Most web-based services are client-server programs. Large risk-management tools (e.g., Innity) are also client-server programs. JAVA makes client-server programming especially easy. 51