Lecture 4 JA V A (46-935) Somesh Jha 1 Inner Classes Flash - - PDF document

lecture 4 ja v a 46 935 somesh jha 1 inner classes flash
SMART_READER_LITE
LIVE PREVIEW

Lecture 4 JA V A (46-935) Somesh Jha 1 Inner Classes Flash - - PDF document

Lecture 4 JA V A (46-935) Somesh Jha 1 Inner Classes Flash bac k to the class. A bstr actT ermStructur e There w as a whic h SlowYieldV olObje ct computed: ( i = 0) Dierence b et w een and c


slide-1
SLIDE 1 Lecture 4 JA V A (46-935) Somesh Jha 1
slide-2
SLIDE 2 Inner Classes
  • Flash
bac k to the A bstr actT ermStructur e class.
  • There
w as a SlowYieldV
  • lObje
ct whic h computed: { (i = 0) Dierence b et w een c
  • mpute
d yield and the market yield { (otherwise) Dierence b et w een c
  • mpute
d volatility and the market volatility.
  • Clumsy!
The
  • b
ject used b y the NewtonR aphson solv er b elongs in the T ermStructur e class.
  • Nob
  • dy
else uses it. 2
slide-3
SLIDE 3 Inner Classes (Con td)
  • Put
a YieldV
  • lObje
ct class inside the T ermStructur e class.
  • Nob
  • dy
else except T ermStructur e class can use the YieldV
  • lObje
ct.
  • These
are called memb er classes.
  • There
are
  • ther
kind
  • f
inner classes. (Read Chapter 5). 3
slide-4
SLIDE 4 Co de F ragmen t /** 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
  • f
the BDT model double r[]; double k[]; //bond yields and yield volatilities //at time double yield[]; double volatilities[]; //nodes[i] points to link list
  • f
//nodes with time i LinkList nodes[]; 4
slide-5
SLIDE 5 class YieldVolObject extends AbstractFunctionObject { //Yield and volatality are computed for the //bond
  • f
that maturity public int maturity; public YieldVolObject() { //call the constructor for the super class super(2); }//end
  • f
constructor //If i==0 calculate the yield and
  • therwise
//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[mat urity-1 ]); } else { double tempVol = slowLogVol(0,0,maturity) ; return(tempVol-volatilitie s[matur ity-1]); } }//end
  • f
evaluate }//end
  • f
YieldVolObject 5
slide-6
SLIDE 6 P
  • in
ts to notice
  • Notice
that the class YieldV
  • lObje
ct is dened inside the T ermStructur e class.
  • Notice
that YieldV
  • lObje
ct has complete access to data
  • f
the T ermStructur e class.
  • Nob
  • dy
can access YieldV
  • lObje
ct from
  • utside.
6
slide-7
SLIDE 7 JA V A pac k ages
  • W
e ha v e
  • r
will co v er some classes from the follo wing pac k ages: { java.applet (Classes concerned with applets) { java.awt (Classes concerned with GUIs) { java.io (Classes concerned with I/O) { java.util (Classes concerned with v arious utilit i es) { java.net (Classes concerned with net w
  • rking)
  • Whole
list
  • f
pac k ages giv en
  • n
page 86-89 in the b
  • k.
7
slide-8
SLIDE 8 JA V A I/O pac k age
  • W
e co v ered v arious kind
  • f
I/O streams.
  • Ho
w to read and write to a le.
  • A
v ery wide v ariet y
  • f
I/O pro vided b y JA V A. 8
slide-9
SLIDE 9 JA V A utlitie s pac k age
  • StingTokenizer
is in the java.util pac k age.
  • Allo
ws us to break a line in to tok ens for parsing.
  • Consider
the follo wing fragmen t
  • f
co de. String line=''hhh:xxx:ccc''; StringTokenizer tokenizer = new StringTokenizer(line,'':'') ; String firstToken = tokenizer.nextToken(); String secondToken = tokenizer.nextToken(); 9
slide-10
SLIDE 10 Other in teresting classes
  • HashTable
  • Date
  • Random
  • Vector
  • Stack
  • Read
ab
  • ut
them
  • n
page 527. 10
slide-11
SLIDE 11 ja v a.lang pac k age
  • This
pac k age is loaded up b y default.
  • String,
Math, System, Double are all in this pac k age.
  • Object
and Exception are also dened in this pac k age.
  • Read
ab
  • ut
it
  • n
page 442. 11
slide-12
SLIDE 12 What is a thread?
  • A
Thr e ad is a lik e a program.
  • Tw
  • threads
run indep enden tly lik e separate programs.
  • Dierence
is that threads run within a program and hence can share v ariables. 12
slide-13
SLIDE 13 Concurren t Programming
  • Threads
enable concurren t programming.
  • Tw
  • separate
tasks can b e going
  • n
in parallel in a single program.
  • Let
us sa y y
  • u
en ter the Blo
  • mb
er g w ebsite. 13
slide-14
SLIDE 14 Concurren t Programming (con td)
  • The
follo wing tasks can b e going
  • n
in parallel: { V arious indexes b eing displa y ed in a b
  • x.
{ Hot news tic k er. { Asking the user to en ter a sto c k sym b
  • l.
  • All
these separate tasks could b e handled b y separate threads. 14
slide-15
SLIDE 15 A small example package threadRelated; public class MyThread extends Thread { public MyThread(String name) { super(name); }//end
  • f
MyThread public void run() { for(int i=0; i < 10; i++) { System.out.println(i+" "+getName()); try { sleep((int)Math.random()*1 000); } catch (InterruptedException e) {}; } System.out.println("DONE! "+getName()); }//end
  • f
run }//end
  • f
MyThread 15
slide-16
SLIDE 16 Constructor
  • A
thread class extends the JA V A class Thread dened in the pac k age java.lang.
  • The
constructor tak es the name
  • f
thread as an argumen t.
  • What
do es super(name) do? 16
slide-17
SLIDE 17 run metho d
  • Whenev
er a thread is started, run metho d is called.
  • The
run metho d in this case go es through the lo
  • p
10 times.
  • sleep((int)Math.ran
dom() *1000 ) susp ends the thread for a random time.
  • What
is Math.random()?
  • getName()
gets the name
  • f
the thread. 17
slide-18
SLIDE 18 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
slide-19
SLIDE 19 Main Program (Con td).
  • There
are t w
  • threads:
thread1 and thread2.
  • First
thread has name put and the second
  • ne
call.
  • The
start metho d
  • n
the thread starts the thread. 19
slide-20
SLIDE 20 When do es a thread stop?
  • A
thread stops when either
  • f
the follo wing ev en ts happ en: { run metho d exits. { stop metho d is called
  • n
the thread. 20
slide-21
SLIDE 21 Output
  • f
the program put 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
slide-22
SLIDE 22 Sync hronization
  • Supp
  • se
that there are t w
  • threads
T 1 and T 2 that share t w
  • v
ariables i and j .
  • Supp
  • se
eac h thread incremen ts i and then incremen ts j b y the v alue
  • f
i.
  • W
e can ha v e t w
  • sample
executions sho wn
  • n
the next slide. 22
slide-23
SLIDE 23 Tw
  • 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
slide-24
SLIDE 24 Inconsistency!
  • First
Exc eution T 1
  • bserv
es j = 6.
  • Se
c
  • nd
Exc eution T 1
  • bserv
es j = 3.
  • Need
to con trol access to shared v ariables.
  • A
nswer: Synchronization 24
slide-25
SLIDE 25 T
  • y
T rading System
  • Eac
h trader en ters the transaction he/she just made.
  • A
pr
  • duc
er thread reads the transaction record and puts in a queue.
  • Consumer
threads read records from the queue and log it. 25
slide-26
SLIDE 26 T
  • y
T rading Example (Fig)

Trader log log Consumer 1 Consumer 2 Producer Queue

Figure 1: A T
  • y
T rading System 26
slide-27
SLIDE 27 Pro ducer 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
  • f
while } catch (IOException e) { System.err.println("Excepti
  • n
  • ccured
"+e.getMessage()); } }//end
  • f
run } 27
slide-28
SLIDE 28 Constructor
  • Constructor
tak es: { Name
  • f
the thread. { The queue to put things in. 28
slide-29
SLIDE 29 run metho d
  • Reads
a line from the screen.
  • Mak
es that line in to a trader-en try .
  • Adds
that trader-en try to the queue. 29
slide-30
SLIDE 30 T raderEn try 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
  • f
first constructor public TraderEntry(String line) { StringTokenizer tokenizer = new StringTokenizer(line); if (tokenizer.countTokens() == NO_OF_ENTRIES) { transactionType = tokenizer.nextToken(); price = Double.valueOf(tokenizer.ne xtToken ()).dou bleValue (); amount = Double.valueOf(tokenizer.n extToke n()).do ubleValu e(); 30
slide-31
SLIDE 31 counterParty = tokenizer.nextToken(); comments = tokenizer.nextToken(); } }//end
  • f
TraderEntry public String toString() { StringBuffer result=new StringBuffer(transactionTyp e); 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
  • f
toString() }//end
  • f
TraderEntry 31
slide-32
SLIDE 32 Constructors
  • First
Constructor This constructor tak es all v e argumen ts explicit l y .
  • Se
c
  • nd
Constructor Second constructor tak es a string and parses the en tries
  • ut
  • f
that. 32
slide-33
SLIDE 33 toString metho d
  • Notice
the use
  • f
StringBuffer in this metho d.
  • This
class represen ts a string
  • f
c haracters.
  • A
StringBuffer
  • b
ject gro ws as things are app ended to it. 33
slide-34
SLIDE 34 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
  • f
run } 34
slide-35
SLIDE 35 Constructor
  • Same
as the pro ducer thread. 35
slide-36
SLIDE 36 run metho d
  • Go
es
  • n
forev er.
  • Eac
h time in the lo
  • p
it gets an en try from the queue.
  • Prin
ts it
  • ut
  • n
the screen.
  • What
happ ens in the follo wing statemen t? System.out.println( tEntr y); 36
slide-37
SLIDE 37 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" ,entryQu eue); ConsumerThread consumer1 = new ConsumerThread("consume-1",e ntryQue ue); ConsumerThread consumer2 = new ConsumerThread("consume-2",e ntryQue ue); prod.start(); consumer1.start(); consumer2.start(); }//end
  • f
main } 37
slide-38
SLIDE 38 Main program
  • Has
  • ne
pro ducer thread prod.
  • Has
t w
  • consumer
threads consumer1 and consumer2.
  • Starts
the three threads. 38
slide-39
SLIDE 39 Queue shared
  • Notice
that the queue entryQueue is shared b et w een the three threads.
  • Need
to synchr
  • nize
access to the queue.
  • Only
  • ne
thread should b e accessing the queue
  • b
ject at an y time. 39
slide-40
SLIDE 40 Queue is empt y
  • What
if a consumer thread w an ts to get a trader-en try and the queue is empt y?
  • Consumer
thread should go in to a wait state.
  • When
a pro ducer thread puts something in the queue, it should notify the waiting consumer thread.
  • Analogous
situation happ ens when the queue is full. 40
slide-41
SLIDE 41 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
  • f
Queue private boolean isEmpty() { return(empty); } private boolean isFull() { return(full); } public synchronized void add(Object
  • bj)
{ while (isFull()) { try { wait(); } 41
slide-42
SLIDE 42 catch (InterruptedException e) { } }//end
  • f
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
  • f
add public synchronized Object delete() { while (isEmpty()) { try { wait(); } catch (InterruptedException e) { } }//end
  • f
while boolean wasFull = isFull(); Object
  • bj=data[back];
if ((back+1)%size == front) empty=true; back = (back+1)%size; full=false; if (wasFull) notifyAll(); return(obj); }//end
  • f
delete public synchronized String toString() { String result=" "; 42
slide-43
SLIDE 43 if (!isEmpty() ) { for(int i=back; i != front; i=(i+1)%size) { result = result + data[i].toString(); result= result+" \n"; } }//end
  • f
if return(result); }//end
  • f
toString }//end
  • f
Queue 43
slide-44
SLIDE 44 Queue class
  • Implemen
ts a circular queue.
  • Figure
  • ut
the logic.
  • The
v ariable size holds the size
  • f
the queue. 44
slide-45
SLIDE 45 delete metho d
  • Deletes
an
  • b
ject from the end
  • f
the queue and returns it.
  • Notice
the denition. public synchronized Object delete()
  • This
means that a thread has to acquire the unique lo ck asso ciated with this
  • b
ject b efore it can execute the delete metho d. 45
slide-46
SLIDE 46 delete metho d (Con td.)
  • Supp
  • se
the consumer1 thread executes the delete metho d and acquires the lo ck.
  • No
w supp
  • se
the prod thread executes the add metho d.
  • The
thread prod blo cks b ecause the lo c k asso ciated with the queue
  • b
ject is with the thread consumer1. 46
slide-47
SLIDE 47 W aiting
  • Supp
  • se
thread consumer2 executes the metho d delete to get a trader-en try .
  • Supp
  • se
the queue is empt y .
  • Thread
consumer2 puts itself in the wait state using the follo wing fragmen t
  • f
co de: while (isEmpty()) { try { wait(); } catch (InterruptedExce ption e) { } }//end
  • f
while 47
slide-48
SLIDE 48 Who w ak es it up?
  • Recall
that consumer2 is w aiting.
  • When
the pro ducer thread prod puts stu in the queue and it w as empt y , it noties the w aiting threads.
  • The
fragmen t
  • f
co de that do es this is: if (wasEmpty) notifyAll(); 48
slide-49
SLIDE 49 Clien t-Serv er Programming
  • Server
runs
  • n
a kno wn host and a p
  • rt.
  • Has
all the heavy-weight stu in it. { Databases with historical data. { Complicated functionali t y (pricing and PDE co de). 49
slide-50
SLIDE 50 Clien t
  • Client
is a light-weight program that uses the serv er.
  • Generally
, the clien t knows the host and the p
  • rt
to connect to the serv er.
  • So
c k ets enable clien t-serv er programming in JA V A. 50
slide-51
SLIDE 51 Clien t-Serv er
  • Most
w eb-based services are clien t-serv er programs.
  • Large
risk-managemen t to
  • ls
(e.g., Innity) are also clien t-serv er programs.
  • JA
V A mak es clien t-serv er programming esp eciall y easy . 51