# chap13 - CS

Λογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 4 χρόνια και 5 μήνες)

86 εμφανίσεις

Chapter 13

Chapter Contents

Chapter Objectives

13.1 Introductory Example: Sorting a List

13.3 Topic: Client
-
Server Networking

13.4 Graphical/Internet Java: Moon
Animation

Part of the Picture: The TCP/IP
Communications Architecture

13.5 The End?

Chapter Objectives

Study the use of threads in Java

Learn about Java's built in support for
communication across a network

See an example of threads used in
animations

Investigate the TCP/IP communications
architecture

13.1 Introductory Example:
Sorting a
List

Recall use of
ArrayList
and

classes

examples of collection classes

A
Collections

class also exists

one of its methods is
sort()

given any List of objects that can be compared, it
will arrange them in ascending order

Our example creates an
ArrayList

of
1,000,000 items

contrasts two different sort routines

Design

First approach:

Build an
ArrayList
of
n
random Integer
values

measure time required for the sort

Second approach:

Build
two

ArrayList

objects of
n/2

random
Integers

a)
measure time to sort first list using
Sorter

b)
sort second list normally

c)
merge the two into a single sorted list of length
n

Anticipated Results

On computer with single CPU, first method
should be slightly faster

On computer with multiple CPUs, second
method slightly faster

thread performing step a) runs on one CPU

step b) performed on different CPU

Program uses 10 trials and takes average
times

Note source code, Figure 13.1

the
portion of the declaration
gives the
ListSorter
execution

Actual Results

On Pentium II uniprocessor

single
-

processor

On Sun multiprocessor

two
-

multiple CPUs allow two threads to run
simultaneously

give 30% faster results

When a program runs, it executes a
series of statements

in sequence

some may be skipped in a branch

some may be repeated in a loop

This series is called a
execution

Programs studied until now are single
-

Java supports

programs

speeds up through parallel processing by
n

pieces, each solved
independently on separate processors

1.
Define a class that extends thread

contains a
run()

method to perform tasks in a

// …

public void run() { … }

// statements the thread is to execute

}

2.
Have the normal thread create an instance
of the class so defined

ListSorter secondSorter = new

ListSorter (list1);

3.
Make this thread begin running by
sending it the
start()
message

secondSorter.start()

Visualized below:

secondSorter = new ListSorter(list1);

secondSorter.start();

2
nd

Implementing the
Runnable
Interface

A class can extend only
one

other
class

if a class needs to extend some
non
-
class
and

run as a distinct
thread, the preceding approach will not
work

Thus the
Runnable
interface
approach

Implementing the
Runnable
Interface

1.
Define a class that
implements
the
Runnable
interface

contains a
run()
method

class ListSorter extends Whatever

implements Runnable

{ // …

public void run() { … }

// statements that thread will execute

}

Implementing the
Runnable
Interface

2.
Have the normal class create an
instance of the class defined in 1.

ListSorter

secondSorter

ListSorter secondSorter =

new ListSorter(list1);

3.
Also have the class create a new
instance of the

class

initialized with object created above

Implementing the
Runnable
Interface

4.
Send the new
object the
start()

message

Note: this is a more complicated
approach

used only to run a separate thread that
must also extend a non
class

Synchronizing Accesses to
Shared Data

Consider an
Account
class which
provides debit and credit methods
which change the balance

If multiple
Transaction

to access the same
Account

object
problems could arise

"Atomic" Operations

Operations that cannot be divided into
"smaller" operations

Example: for
myBalance

being
accessed by either the
debit()
or
credit()

time

these methods are
not

atomic at the byte
-
code level

each has about four separate steps

Non Atomic Operations in

Assume
credit()
and
debit()

are in

Both will

1.

2.
create a temp value

3.
add to (or subtract from) the temp value

4.
replace the old balance with the temp value

If each step is happening at about the same
time

each replaces the old balance with its own temp value

the action of the other, giving an
incorrect new balance value !!!

Making Methods Atomic

Use the keyword
synchronized
to
declare each method that accesses the
critical information

class Account{

. . .

synchronized public void debit(double amount)

{ … }

synchronized public void credit(double amount

{ … }

private myBalance;

}

Making Methods Atomic

sends a synchronized message to an object

and … no other thread is executing a
synchronized method on that object

Then …

Java
locks

the object

other synchronized methods cannot access
the object until the first terminates

13.3 Topic: Client
-
Server
Networking

Java has built
-
in support for programs
to communicate across a network

Client
-
server model has two kinds of
programs

server

programs that wait for other
programs (clients) to request service

client

programs that contact servers and
ask them to perform a service

Client
-
Server Networking

Example

web browsers

User clicks on a link, browser (client)
program contacts server at that link site

Server retrieves requested file, sends it
to browser (client)

Modern e
-
mail programs work in a similar
fashion

Sockets

Communication endpoints by which
information

Server creates a
ServerSocket

waits for clients to connect to it

Client creates a
Socket

to connect to
that server's
ServerSocket

Socket Details

Sockets must be distinct from all others

Java requires special integer value,
called a
port

Ordered pair

(ComputerName, portNumber)

is the unique socket identification

Example: A Daytime Client

To illustrate how a
Socket
uses a port

Note source code for TCP daytime
client, Figure 13.3

Features

Client
Socket

initialization

connects to
ServerSocket
at that time

Socket

constructor needs name of remote
host and port of socket needed

Socket S = new Socket(remoteHost, DAYTIME_PORT);

Connection alone not enough

must be able to read from it

considered an input operation

Input stream declared

S.getInputStream() ));

Input stream accessed

Writing to a Socket

The server sending the data must
declare the output stream

PrintWriter W = new PrintWriter(

S.getOutputStream(), true);

// true enables auto
-
flush

Server then transmits the information

w.println(" … ");

ServerSocket
Initialization

Client socket initialization

specify
remoteHost
and port

Socket s = new Socket(remoteHost,port);

ServerSocket
created by
server

no remote host to be specified

specify port only

if 0 specified,
sS

will be given any free port

ServerSocket sS = new ServerSocket(port);

Accepting a Connection

The
ServerSocket
constructor builds,
initializes an object

must also explicitly tell the object to listen for
incoming connections

Socket s = sS.accept()

Results of
accept()

1.
server sending the
accept()

blocks until a
client requests connection

2.
accept()

builds, sends a
Socket

that is the
actual end
-
point for connection back to client

ServerSocket

Done in same way as
Socket
is
treated

Build a

or
PrintWriter

as a wrapper for the
ServerSocket

Then use

or
println()

to communicate with the client

Closing a Socket

Consider it a stream

closed with the
close()

command

If socket not closed

programs can become "zombie processes"

Example: A Daytime Server

Behavior

1.
Build
ServerSocket
to listen for
connections on port 1013

2.
Repeat the following

a)
use
accept()

to accept connection request

b)
Build
PrintWriter

for resulting Socket

c)
Get current day, time from system

d)
Write current day, time to
PrintWriter

e)
Close
PrintWriter

(and
Socket
)

Note source code, example
of run, Figure 13.4

Program of Figure 13.4 is single
-

then processes

uses a forever loop

response possible

Longer task would cause backlog of
client requests

Each iteration of the processing loop will:

accept connection request

create a handler thread for that client

server thread immediately returns to top of
processing loop

for( ; ; ) {

Socket sessionSocket = myServerSocket.accept();

// create new thread for service using

// sessionSocket

}

Example:

Server will read lines of text client
sends

echo back each line

may be multiple lines, time consuming

EchoServer
class

builds its
ServerSocket

repeatedly

invokes
accept()

creates new
EchoHandler

each request

Echo Server

Source code for multithreaded echo server,
Figure 13.5

Echo
-
handler thread source code, Figure 13.6

Echo Client program, figure 13.7

If providing a server's service takes less time
than creating a thread, then a single
-

13.4 Graphical/Internet Java:

Moon Animation

Application will present a stationary
moon

use animation to show change of
appearance over time

use "slider" to control speed of animation

use pause, play, forward, backward
buttons

Behavior

Moon Phases

Faster

Slower

||

Process States

Running state (view on previous slide)

Paused state

shows Backward, Forward, Play buttons

removes slider, pause

running

paused

Pause pressed

Play pressed

Forward
pressed

Backward
pressed

Strategy

getImage()
command

Iterate through array in circular fashion

display in sequence

Must also listen for user
-
generated
events (buttons pushed)

Listening and animating
at the same
time

Source Code

Note source code, Figure 13.8

Getting the Images

in constructor, for loop

routine waits for all images before
displaying, no flicker

Constructor also starts the thread in
running state

paintComponent()
method used to
draw images

Source Code

Defining
behavior

run method repeatedly checks for pause
and then increments image and repaints

Pausing execution

synchronized
pause()
method sets flag

synchronized
waitIfPaused()

method
calls
wait()

synchronized
go()

changes flag

Behind the Scenes

Java objects have an attribute called a
"monitor"

Used for synchronization of methods

A class must "own the monitor" before it can
execute a synchronized method

Synchronized methods each have a lock,
checked when a thread seeks to execute

Thread suspended on "lock list" while waiting
to own the monitor

Behind the Scenes

synchronized method which invokes
wait()

Java suspends thread on "waiting list" to
be notified

left on waiting list until another
notify()

notify()

transfers thread to lock list to
wait for re
-
acquisition of the monitor

MoonPhases
Class

Note source code, Figure 13.9

New feature used, slider control

mySlider = new JSlider(0,1000,

INITIAL_DELAY);

implements
ChangeListener
interface

requires
stateChanged()
method

actionPerformed()

method

determines which button pressed,

sends appropriate message to
MoonAnimator

Part of the Picture: The TCP/IP
Communications Architecture

for interconnection software

Before standards developed, we need …

structure or protocol architecture

Two current architectures

TCP/IP

OSI (Open Systems Interconnection)

Most widely
used

Organization of TCP/IP

Five relatively independent layers:

1.
Physical layer

connects computer with network

2.
Network access layer

data across a network for end systems

3.
Internet layer

procedures for data to traverse multiple
interconnected networks

Organization of TCP/IP

Five relatively independent layers:

4.
Host
-
to
-
host layer or transport layer

concerned with reliable data exchange

5.
Application layer

supports variety of applications

separate modules needed for each
application

Operation of TCP/IP

Consider a sample operation

application associated
with port 1 at host A wishes to send message to
another application, port 2, host A

Application gives message to CCP

send to host B, port 2

TCP gives message to IP

send to host B (need not mention port)

note that control info and data may be broken into smaller
blocks of data

blocks include TCP header and TCP segment

header can include destination port, sequence number,
checksum

Operation of TCP/IP

IP hands message to network access layer

send it to router J

IP also appends header of control information

Network layer appends header, transmits packet to router

headers contain information needed for routing

include destination subnetwork address and facilities
requests

examined

datagram directed to destination

At destination, reverse process occurs

TCP and UDP

Note header format for TCP, Figure
13.13a

UDP

User Datagram Protocol

provides connectionless service for
application
-
level procedures

does
not

guarantee delivery, preservation
of sequence, duplication protection

provides message sending with minimum
protocol

IP and IPv6

Provides functional enhancements over
current IP

Accommodates higher transmission
speeds, mixing of data streams

Handles increasing number of

TCP/IP Applications

Simple mail transfer protocol (SMTP)

basic electronic mail

features include mailing lists, return
receipts, forwarding

uses TCP to send it to SMTP module
elsewhere

File transfer protocol (FTP)

accommodates both text and binary files

enables user access control

TCP/IP Applications

TELNET provides remote logon
capability

user at one computer can log on to remote
computer

user can function as if directly connected
to remote location

terminal traffic between user and server
carried on TCP connection

13.5 The End?

End of the text … but …
not

the end of Java!

we have covered only a small part of its
capabilities

We have concentrated mainly on
programming …

computer science is so much more

Take what you have learned

use it

enlarge upon it!