Instructor Inputs
Session 13 ¤NIIT Instructor Inputs 13.3
This session covers Chapter 13.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
Creating an application by using a class and its objects
Variable declaration and initialization in the class program
At times, a program needs to perform multiple tasks concurrently. For example, a Web
browser displaying a sports Web page runs a Java applet that spins a football in the
corner, but leaves the scrollbar active so that the Web page can be traversed at the same
time. The Web browser is multithreaded, which enables this flexibility. This session
describes how to set up multiple threads in a single program so that you can perform
multiple tasks simultaneously.
Every Java program contains at least one thread, which is the main thread. When a Java
program starts, the JVM creates the main thread and calls the main() method of the
program within that thread. More threads can be created by using the Thread constructor
or by instantiating classes that extend the Thread class.
While conducting the session, you need to explain the synchronization of threads.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 13.4 Instructor Inputs ¤NIIT
Slide 1
Slide 1 of 24 Session 13 Ver. 1.0
Java Programming Language
In this session, you will learn to:
Define a thread
Create separate threads in a Java technology program,
controlling the code and data that are used by that thread
Control the execution of a thread and write platform
independent code with threads
Describe the difficulties that might arise when multiple threads
share data
Use wait and notify to communicate between threads
Use synchronized to protect data from corruption
Objectives
Use Slide 1 to share the session objectives with the students.
Slide 2
Slide 2 of 24 Session 13 Ver. 1.0
Java Programming Language
Threads
Threads are a virtual CPU.
The three parts of at thread are:
CPU
Code
Data
A thread or
execution context
Use Slide 2 to introduce the concept of threads.
Threading enables multiple activities to coexist within a single process. Java is the first
mainstream programming language that explicitly includes threading within the language ¤NIIT Instructor Inputs 13.5
itself, rather than treating threading as a feature of the underlying operating system.
Threads are sometimes referred to as lightweight processes. Like processes, threads are
independent, concurrent paths of execution that run through a program. Each thread has
its own stack, its own program counter, and its own local variables.
Slide 3
Slide 3 of 24 Session 13 Ver. 1.0
Java Programming Language
Creating the Thread
Extend the class from Thread Class. For example:
public class HelloRunner extends Thread
{
//code
}
Implement the Runnable interface. For example:
class HelloRunner implements Runnable
{
//code
}
Use Slide 3 to discuss ways to create a thread in a Java program. Every Java program
contains at least one thread, which is the main thread. Additional threads are created
through the Thread constructor or by instantiating classes that extend the Thread class.
Java threads can create other threads by instantiating a Thread object directly or an object
that extends Thread. 13.6 Instructor Inputs ¤NIIT
Slide 4
Slide 4 of 24 Session 13 Ver. 1.0
Java Programming Language
Creating the Thread (Contd.)
Multithreaded programming has following characteristics:
Multiple threads are from one Runnable instance.
Threads share the same data and code. For example:
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Use Slide 4 to explain that a Java program can have many threads.
Multithreading is useful even in programs running on a single-processor computer. In this
scenario, Thread 2 runs while Thread 1 is blocked, waiting for I/O. The I/O action can
take place in parallel with the CPU running the other thread. In a single-threaded case,
Thread 2 waits until Thread 1 has finished.
Slide 5
Slide 5 of 24 Session 13 Ver. 1.0
Java Programming Language
Starting the Thread
Use the start() method
Place the thread in a runnable state¤NIIT Instructor Inputs 13.7
Use Slide 5 to explain how to start a thread.
A thread does not actually begin to execute until another thread calls the start() method on
the Thread object for the new thread. The Thread object exists before its thread actually
starts, and it continues to exist after its thread exits. This enables you to control or obtain
information about a thread you have created, even if the thread has not started yet or has
already completed. It is not advisable to start() threads from within a constructor. This
might expose partially constructed objects to the new thread. If an object owns a thread, it
should provide a start() method to start the thread instead of starting it from the
constructor.
Slide 6
Slide 6 of 24 Session 13 Ver. 1.0
Java Programming Language
Thread Scheduling
Runnable
New
Running
Blocked Dead
start() run() Completes
Scheduler
Event Blocked Unblocked
Fundamental Thread State Diagram:13.8 Instructor Inputs ¤NIIT
Slide 7
Slide 7 of 24 Session 13 Ver. 1.0
Java Programming Language
Thread Scheduling Example:
public class Runner implements Runnable {
public void run() {
while (true) {
// do lots of interesting stuff
// Give other threads a chance
try {
Thread.sleep(10);
} catch (InterruptedException e)
{
// This thread’s sleep was interrupted by another thread
}
}
}
}
Thread Scheduling (Contd.)
One of Thread
Scheduling Method
Use Slides 6 and 7 to explain the fundamental thread state diagram and provide the
example of using sleep() method to perform scheduling.
Slide 8
Slide 8 of 24 Session 13 Ver. 1.0
Java Programming Language
Terminating a Thread
The thread comes to the end of its run() method.
The thread throws an Exception or Error that is not caught.
Another thread calls one of the deprecated stop()
methods.
Use Slide 8 to explain how to terminate a thread. ¤NIIT Instructor Inputs 13.9
A thread can end in one of the following ways:
The thread comes to the end of its run() method.
The thread throws an exception or error that is not caught.
Another thread calls one of the deprecated stop() methods.
Deprecated means they still exist. You should not use them in a new code and should
strive to eliminate them in the existing code. When all the threads within a Java program
are completed, the program exits.
Slide 9
Slide 9 of 24 Session 13 Ver. 1.0
Java Programming Language
Basic Control of Threads
Test Threads:
isAlive()
Access Thread Priority:
getPriority()
setPriority()
Put Threads on Hold:
Thread.sleep() // static method
join()
Thread.yield() // static method
The Thread API includes a sleep() method, which causes the current thread to go into a
wait state until the specified amount of time has elapsed or until the thread is interrupted
by another thread by calling Thread.interrupt() on the current thread’s Thread object.
If a thread is interrupted by a call to Thread.interrupt(), the sleeping thread throws an
InterruptedException.
The Thread.yield() method is similar to Thread.sleep(), but instead of sleeping, it pauses
the current thread momentarily so that the other thread can run.
Use the code given on Slide 10 to explain the join() method. The Thread API contains a
method for waiting for another thread to complete the join() method. When you call
Thread.join(), the calling thread blocks until the target thread completes. Thread.join() is
generally used by programs that use threads to partition large problems into smaller ones,
giving each thread a piece of the problem. 13.10 Instructor Inputs ¤NIIT
Slide 10
Slide 10 of 24 Session 13 Ver. 1.0
Java Programming Language
Use of join() method:
public static void main(String[] args) {
Thread t = new Thread(new Runner());
t.start();
// Do stuff in parallel with the other thread for a while
// Wait here for the other thread to finish
try {
t.join();
}
catch (InterruptedException e)
{
// the other thread came back early
}
// Now continue in this thread
}
Basic Control of Threads (Contd.)
Use Slides 9 and 10 to explain how to control threads.
Slide 11
Slide 11 of 24 Session 13 Ver. 1.0
Java Programming Language
The Object Lock Flag
Every object has a flag that is a type of lock flag.
The synchronized enables interaction with the lock flag.
Object this Thread before synchronized(this)
public void push (char c)
{
synchronized(this) {
data[idx] = c;
idx++;
}
}¤NIIT Instructor Inputs 13.11
Slide 12
Slide 12 of 24 Session 13 Ver. 1.0
Java Programming Language
The Object Lock Flag (Contd.)
Object this Thread after synchronized(this)
public void push (char c)
{synchronized(this)
{
data[idx] = c;
idx++;
}
}
Slide 13
Slide 13 of 24 Session 13 Ver. 1.0
Java Programming Language
The Object Lock Flag (Contd.)
Another thread, trying to execute
synchronized(this)
public char pop(char c)
{
synchronized(this)
{
idx–;
return data[idx];
}
}
Object this
lock flag missing
Waiting for
object lock
Use Slides 11, 12, and 13 to explain the object lock flag. When multiple threads access
the same data item (such as a static field, an instance field of a globally accessible object,
or a shared collection), you need to ensure that they coordinate their access to the data so
that both see a consistent view of the data and neither steps on the other’s changes. The
Java language provides two keywords for this purpose, synchronized and volatile. When
accessing variables from more than one thread, access must be properly synchronized. 13.12 Instructor Inputs ¤NIIT
The basic rule for synchronizing for visibility is that you must synchronize whenever you
are:
Reading a variable that may have been last written by another thread.
Writing a variable that may be read next by another thread.
Slide 14
Slide 14 of 24 Session 13 Ver. 1.0
Java Programming Language
Releasing the Lock Flag
The lock flag is released in the following events:
Released when the thread passes the end of the synchronized
code block
Released automatically when a break, return, or exception is
thrown by the synchronized code block
Use Slide 14 to explain how to release the lock that is placed by the synchronized
keyword. ¤NIIT Instructor Inputs 13.13
Slide 15
Slide 15 of 24 Session 13 Ver. 1.0
Java Programming Language
All access to delicate data should be synchronized.
Delicate data protected by synchronized should be private.
The following two code segments are equivalent:
public void push(char c)
{
synchronized(this) {
// The push method code
}
}
public synchronized void push(char c)
{
// The push method code
}
Using synchronized
Use Slide 15 to share information about the synchronized keyword.
Slide 16
Slide 16 of 24 Session 13 Ver. 1.0
Java Programming Language
Thread State Diagram with Synchronization:
Using synchronized (Contd.)
New
Running
Blocked Dead
start() run() Completes
Scheduler
Event Blocked
Runnable
Blocked in
Object’s Lock
Pool
Unblocked
Synchronized Lock Acquired
Use Slide 16 to explain the thread state diagram with synchronization. 13.14 Instructor Inputs ¤NIIT
Slide 17
Slide 17 of 24 Session 13 Ver. 1.0
Java Programming Language
Deadlock
A deadlock has the following characteristics:
It is two threads, each waiting for a lock from the other.
It is not detected or avoided.
Deadlock can be avoided by:
Deciding on the order to obtain locks
Adhering to this order throughout
Releasing locks in reverse order
Use Slide 17 to explain the deadlock situation.
A deadlock usually occurs when there are multiple processes contending for exclusive
access to multiple locks. A set of processes or threads is said to be deadlocked when each
is waiting for an action that only one of the others can perform.
The most common form of deadlock is when Thread 1 holds a lock on Object A and is
waiting for the lock on Object B, and Thread 2 holds the lock on Object B and is waiting
for the lock on Object A. Neither thread will ever acquire the second lock or relinquish
the first lock. They will simply wait forever.
To avoid a deadlock, ensure that when acquiring multiple locks, you always acquire the
locks in the same order in all threads. ¤NIIT Instructor Inputs 13.15
Slide 18
Slide 18 of 24 Session 13 Ver. 1.0
Java Programming Language
Thread Interaction
wait and notify Methods
Scenario:
Consider yourself and a cab driver as two threads.
Problem:
How do you determine when you are at your destination?
Solution:
You notify the cab driver of your destination and relax
The driver drives and notifies you upon arrival at your destination
Slide 19
Slide 19 of 24 Session 13 Ver. 1.0
Java Programming Language
Thread Interaction (Contd.)
Thread interactions include:
The wait() and notify() methods
The pools:
Wait pool
Lock pool
Use Slides 18 and 19 to explain about the wait() and notify() methods.
The Object class defines the wait(), notify(), and notifyAll() methods. To execute any of
these methods, you need to hold the lock for the associated object. Wait() causes the
calling thread to sleep until it is interrupted with Thread.interrupt(), the specified timeout
elapses, or another thread wakes it up with notify() or notifyAll(). 13.16 Instructor Inputs ¤NIIT
When the notify() method is invoked on an object and if there are any threads waiting on
that object through wait(), one thread will be awakened. When the notifyAll() method is
invoked on an object, all threads waiting on that object are awakened.
These methods are the building blocks of more sophisticated locking, queuing, and
concurrency code. However, the use of notify() and notifyAll() is complicated. In
particular, using notify() instead of notifyAll() is risky. Use notifyAll() unless you really
know what you’re doing.
Slide 20
Slide 20 of 24 Session 13 Ver. 1.0
Java Programming Language
Thread Interaction (Contd.)
Thread State Diagram with wait() and notify() methods:
New
Running
Blocked
Dead
start() run() Completes
Scheduler
Event Blocked
Runnable
Blocked in
Object’s
Lock Pool
Blocked in
Object’s
Wait Pool
Synchronized
notify() or
interrupt()
wait()
Unblocked
Lock Acquired
Use Slide 20 to explain the thread state diagram with the wait() and notify() methods. ¤NIIT Instructor Inputs 13.17
Slide 21
Slide 21 of 24 Session 13 Ver. 1.0
Java Programming Language
Monitor Model for Synchronization
Leave shared data in a consistent state
Ensure programs cannot deadlock
Do not put threads expecting different notifications in the
same wait pool.
Use Slide 21 to introduce the monitor model of synchronization.
Slide 22
Slide 22 of 24 Session 13 Ver. 1.0
Java Programming Language
Lets see how to create a Java class that represents a
separate thread of control flow.
Demonstration
Give a demo to the students to show how to create a Java class that represents a separate
thread of control flow. 13.18 Instructor Inputs ¤NIIT
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod13_threads\ DemoProject.
Slide 23
Slide 23 of 24 Session 13 Ver. 1.0
Java Programming Language
Summary
In this session, you learned that:
Threads are a virtual CPU.
The three parts of at thread are CPU, Code, and Data.
Thread can be created by extend the class from Thread Class
or by implementing Runnable interface.
A Java program can have multiple threads.
Thread need to start by using start() method.
Various states of thread are runnable, running, and blocked.
sleep() method pauses the thread for given amount of time.
The thread dies when run() method completes.
sleep(), join(),and yield() methods put the thread on
hold.
Use getPriority() method to determine the current priority
of the thread.
Slide 24
Slide 24 of 24 Session 13 Ver. 1.0
Java Programming Language
Summary (Contd.)
When multiple threads are working on shared data,
synchronized keyword should be used to maintain the
consistency of the data.
Deadlock is the situation where two threads, each waiting for a
lock from the other.
wait() and notify() are methods for thread
communication.
Use Slides 23 and 24 to summarize the key points of this session. ¤NIIT Instructor Inputs 13.19
The following section provides some extra inputs on the important topics covered in the
SG.
A few simple guidelines to be followed when writing synchronized blocks to avoid the
risks of deadlock and performance hazards are:
Keep blocks short. Synchronized blocks should be short, as short as possible while
still protecting the integrity of related data operations. In addition, move
thread-invariant preprocessing and postprocessing out of synchronized blocks.
Do not invoke methods on other objects while holding a lock. This may sound
extreme, but it eliminates the most common source of deadlock.
To maintain proper visibility across threads, use synchronized or volatile statements to
ensure that changes made by one thread are visible by another whenever a nonfinal
variable is shared among several threads.
You need to synchronize when:
Reading a variable that may have been last written by another thread.
Writing a variable that may be read next by another thread.
There are a few cases where you need not synchronize to propagate data from one thread
to another because JVM implicitly performs synchronization. These cases include:
When data is initialized by a static initializer, an initializer on a static field, or in a
static{} block
When accessing final fields
When an object is created before a thread is created
When an object is already visible to a thread that it is then joined with
Additional Inputs
Guidelines for Synchronization
Need for Synchronization 13.20 Instructor Inputs ¤NIIT
How many threads can you create?
Ans: By default, on a Win32 machine, each native thread gets one MB or 1024*1024
bytes of stack space reserved for it. The memory is not actually allocated. If it were, you
would run out of memory with dozens of threads instead of hundreds. The space needs to
be reserved as a contiguous block of memory so that the stack can grow as needed. In
Win32, the maximum amount of memory is 2 GB, which corresponds to 2,000 threads,
each reserving 1MB of memory. This is the upper limit. In practice, you might run out of
other OS resources before running out of memory. Each thread has some system
resources that are used to manage the thread register storage area, thread-local storage,
state information, exception condition info, etc. You should design your programs so that
you use threads only where necessary. It is almost always a mistake to have one thread
per object. Successful programs are much more likely to have 5 threads or fewer than 500.
How can you create a thread and start it running?
Ans: You can create an instance of a thread or a thread subclass, and invoke start()
method on that instance.
How can you specify pause times in your program?
Ans: You can specify pause times by using the sleep method of the Thread class.
How can you stop a thread and start a new thread in its place?
Ans: To stop a thread and start a new thread in its place, use the cooperative approach
wherever possible. Set a flag to indicate that the thread should stop, but let the targeted
thread itself check for the flag and find a safe place to stop.
How does the stop method of a thread work? Can you restart a stopped thread?
Ans: The stop method stops a thread permanently. This thread cannot be run again.
FAQs
———————————————————————————————————————
Instructor Inputs
Session 14 ¤NIIT Instructor Inputs 14.3
This session covers Chapters 14 and 15.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
Writing programs by using exception handling
Implementing file I/O methods
This session covers the stream I/O mechanism. It discusses how data can be read and
written by using streams. In addition, it discusses network implementation in Java
programs.
You can start the session by explaining the I/O operations requirement. List the
differences between byte streams and character streams. Explain that networking is
required to provide services to any client through network servers. In this case, the
client/server communication needs to be established to access services provided by the
server to the client.
Slide 1
Slide 1 of 26 Session 14 Ver. 1.0
Java Programming Language
In this session, you will learn to:
Describe Input/Output fundamentals
Construct node and processing streams, and use them
appropriately
Distinguish readers and writers from streams, and select
appropriately between them
Develop code to set up the network connection
Understand the TCP/IP Protocol
Use ServerSocket and Socket classes for implementation of
TCP/IP clients and servers
Objectives
Use Slide 1 to share the session objectives with the students.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 14.4 Instructor Inputs ¤NIIT
Slide 2
Slide 2 of 26 Session 14 Ver. 1.0
Java Programming Language
I/O Fundamentals
A stream can be thought of as a flow of data from a source
or to a sink.
A source stream initiates the flow of data, also called an
input stream.
A sink stream terminates the flow of data, also called an
output stream.
Sources and sinks are both node streams.
Types of node streams are files, memory, and pipes
between threads or processes.
Use Slide 2 to explain I/O fundamentals.
An I/O stream represents an input source or an output destination. A stream can represent
various kinds of sources and destinations, including disk files, devices, other programs,
and memory arrays.
Streams support various kinds of data, including simple bytes, primitive data types,
localized characters, and objects. Some streams simply pass on data; others manipulate
and transform the data in useful ways. ¤NIIT Instructor Inputs 14.5
Slide 3
Slide 3 of 26 Session 14 Ver. 1.0
Java Programming Language
I/O Fundamentals (Contd.)
Writer OutputStream Sink streams
Reader InputStream Source streams
Character Streams Byte Streams Stream
The fundamental stream classes are:
Slide 4
Slide 4 of 26 Session 14 Ver. 1.0
Java Programming Language
Data Within Streams
Java technology supports two types of streams:
character
byte
Input and output of character data is handled by readers
and writers.
Input and output of byte data is handled by input streams
and output streams.
Normally, the term stream refers to a byte stream.
The terms reader and writer refer to character streams.
Use Slides 3 and 4 to explain the fundamental stream class, byte streams, and character
streams.
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream
classes are descended from InputStream and OutputStream classes. 14.6 Instructor Inputs ¤NIIT
All character stream classes are descended from Reader and Writer classes. As with byte
streams, there are character stream classes that specialize in file I/O. These are FileReader
and FileWriter.
Slide 5
Slide 5 of 26 Session 14 Ver. 1.0
Java Programming Language
The InputStream Methods
The three basic read methods are:
int read()
int read(byte[] buffer)
int read(byte[] buffer, int offset, int
length)
Other methods include:
void close()
int available()
long skip(long n)
boolean markSupported()
void mark(int readlimit)
void reset()
Slide 6
Slide 6 of 26 Session 14 Ver. 1.0
Java Programming Language
The OutputStream Methods
The three basic write methods are:
void write(int c)
void write(byte[] buffer)
void write(byte[] buffer, int offset, int
length)
Other methods include:
void close()
void flush()
Use Slides 5 and 6 to explain InputStream and OutputStream methods. ¤NIIT Instructor Inputs 14.7
Slide 7
Slide 7 of 26 Session 14 Ver. 1.0
Java Programming Language
The three basic read methods are:
int read()
int read(char[] cbuf)
int read(char[] cbuf, int offset, int
length)
Other methods include:
void close()
boolean ready()
long skip(long n)
boolean markSupported()
void mark(int readAheadLimit)
void reset()
The Reader Methods
Slide 8
Slide 8 of 26 Session 14 Ver. 1.0
Java Programming Language
The basic write methods are:
void write(int c)
void write(char[] cbuf)
void write(char[] cbuf, int offset, int
length)
void write(String string)
void write(String string, int offset, int
length)
Other methods include:
void close()
void flush()
The Writer Methods
Use Slides 7 and 8 to explain Reader and Writer methods. 14.8 Instructor Inputs ¤NIIT
Slide 9
Slide 9 of 26 Session 14 Ver. 1.0
Java Programming Language
Node Streams
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
Pipe
N/A StringReader
StringWriter
Memory: string
ByteArrayInputStream
ByteArrayOutputStream
CharArrayReader
CharArrayWriter
Memory: array
FileInputStream
FileOutputStream
FileReader
FileWriter
File
Byte Streams Character Streams Type
Various types of Character and Byte Stream classes are:
Use Slide 9 to explain the concept of the node stream class. You can explain this concept
by giving a small example: when you need to read data from a text file and transfer this
data to another text file, you use node streams.
Node streams can be used to write to file systems or even across sockets. This means you
can easily transfer a flattened object across a network wire and have it rebuilt on the other
side. ¤NIIT Instructor Inputs 14.9
Slide 10
Slide 10 of 26 Session 14 Ver. 1.0
Java Programming Language
I/O Stream Chaining
Input Stream Chain:
FileInputStream BufferedInputStream DataInputStream
Data Source
Program
Program Data Sink
FileOutputStream
BufferedOutputStream
DataOutputStream
Output Stream Chain:
Use Slide 10 to explain input stream chain and output stream chain.
Slide 11
Slide 11 of 26 Session 14 Ver. 1.0
Java Programming Language
Processing Streams
ObjectInputStream
ObjectOutputStream
Performing object
serialization
DataInputStream
DataOutputStream
Performing data
Conversion
LineNumberInputStream LineNumberReader Counting
InputStreamReader
OutputStreamWriter
Converting between
bytes and character
FilterInputStream
FilterOutputStream
FilterReader
FilterWriter
Filtering
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
Buffering
Byte Streams Character Streams Type
Processing Streams are Node Streams that use filters in
between while transferring the data.
Various types of Processing Streams are:
Use Slide 11 to explain the concept of processing streams. Processing streams are node
streams that use filters while transferring data. For example, when you read data from the
standard input and want to save the same data in the text file, you need to use filters,
called processing streams. 14.10 Instructor Inputs ¤NIIT
Slide 12
Slide 12 of 26 Session 14 Ver. 1.0
Java Programming Language
InputStream
The InputStream Class Hierarchy:
Slide 13
Slide 13 of 26 Session 14 Ver. 1.0
Java Programming Language
OutputStream
The OutputStream Class Hierarchy:¤NIIT Instructor Inputs 14.11
Slide 14
Slide 14 of 26 Session 14 Ver. 1.0
Java Programming Language
Reader Class
The Reader Class Hierarchy:
Slide 15
Slide 15 of 26 Session 14 Ver. 1.0
Java Programming Language
Writer Class
The Writer Class Hierarchy:
Slides 12, 13, 14, and 15 can be used to explain InputStream class hierarchy,
OutputStream class hierarchy, Reader class hierarchy, and Writer class hierarchy,
respectively. 14.12 Instructor Inputs ¤NIIT
Slide 16
Slide 16 of 26 Session 14 Ver. 1.0
Java Programming Language
Networking
Basics of Networking:
Computers running on the Internet communicating to each
other using the Transmission Control Protocol (TCP) / Internet
Protocol (IP).
Server. foo.com
3000
Client.bar.com
18000
Client.baz.com
18002
Port no.
Slide 17
Slide 17 of 26 Session 14 Ver. 1.0
Java Programming Language
Networking (Contd.)
Networking with Java Technology:
Sockets:
Sockets hold two streams, an input stream and an output stream.
Each end of the socket has a pair of streams.
Setting Up the Connection:
Setup of a network connection is similar to a telephone.
One end must dial the other end, which must be listening.¤NIIT Instructor Inputs 14.13
Slide 18
Slide 18 of 26 Session 14 Ver. 1.0
Java Programming Language
Networking (Contd.)
To address the connection, include the following:
The address or name of remote machine.
A port number to identify the purpose at the server.
Port numbers range from 0–65535
Use Slides 16, 17, and 18 to explain the basic concept of networking.
Slide 19
Slide 19 of 26 Session 14 Ver. 1.0
Java Programming Language
Networking (Contd.)
Java Networking Model:
Server
Client
Socket(host, port#)
(Attempt to connect)
SeverSocket(port#)
ServerSocket.accept()
Socket()
OutputStream
InputStream
Socket.close()
OutputStream
InputStream
Socket.close()
Register with
this service
Wait for a
connection
Use Slide 19 to explain the Java networking model. 14.14 Instructor Inputs ¤NIIT
Slide 20
Slide 20 of 26 Session 14 Ver. 1.0
Java Programming Language
ServerSocket and Socket Classes
Code Snippet for Creating Minimal TCP/IP Server:
ServerSocket s = null;
s = new ServerSocket(5432); //Register your
service on port 5432
while (true) // Run the listen/accept loop forever
{
Socket s1 = s.accept(); // Wait here and listen
for a connection
OutputStream s1out = s1.getOutputStream();
// Get output stream associated with the socket
BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(s1out));
bw.write(“Hello Net World!\n”); // Send your
string!
Use Slide 20 to explain the code required to create a simple server program.
Slides 21
Slide 21 of 26 Session 14 Ver. 1.0
Java Programming Language
ServerSocket and Socket Classes (Contd.)
bw.close(); // Close the connection, but not the
server socket
s1.close();
}
Code Snippet for Creating Minimal TCP/IP Client:
// Open your connection to a server, at port 5432
// localhost used here
Socket s1 = new Socket(“127.0.0.1”, 5432);
// Get an input stream from the socket
InputStream is = s1.getInputStream();
// Decorate it with a “data” input stream
DataInputStream dis = new
DataInputStream(is);¤NIIT Instructor Inputs 14.15
Slides 22
Slide 22 of 26 Session 14 Ver. 1.0
Java Programming Language
ServerSocket and Socket Classes (Contd.)
// Read the input and print it to the screen
System.out.println(dis.readUTF());
// When done, just close the steam and connection
dis.close();
s1.close();
Use Slides 21 and 22 to explain the code required to create a simple client program.
Slide 23
Slide 23 of 26 Session 14 Ver. 1.0
Java Programming Language
Lets see how to create a TCP based Java client, and use
user-provided system properties to drive a Java program.
Demonstration
Give a demo to show how to create a TCP based Java client, and use user-provided
system properties to drive a Java program. 14.16 Instructor Inputs ¤NIIT
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod15_network\DemoProject.
Slide 24
Slide 24 of 26 Session 14 Ver. 1.0
Java Programming Language
Summary
In this session, you learned that:
A stream is a flow of data from a source or to a sink.
A source stream are also called an input stream.
A sink stream terminates the flow of data, also called an output
stream.
InputStream, OutputStream, Reader, and Writer are
fundamental stream classes.
Three basic read methods of InputStream class are:
int read()
int read(byte[] buffer)
int read(byte[] buffer, int offset, int length)
Three basic write methods of OutputStream class are:
void write(int c)
void write(byte[] buffer)
void write(byte[] buffer, int offset, int length)
Slide 25
Slide 25 of 26 Session 14 Ver. 1.0
Java Programming Language
Summary (Contd.)
Three basic read methods of Reader class are:
int read()
int read(char[] cbuf)
int read(char[] cbuf, int offset, int length)
The basic write methods of Writer class are:
void write(int c)
void write(char[] cbuf)
void write(char[] cbuf, int offset, int length)
void write(String string)
void write(String string, int offset, int length)
FileReader and FileWriter are file type character
streams.
FileInputStreaam and FileOutputStream are byte
streams classes.
ServerSocket and Socket are main classes to establish the
networking in Java Programs.¤NIIT Instructor Inputs 14.17
Slide 26
Slide 26 of 26 Session 14 Ver. 1.0
Java Programming Language
Summary (Contd.)
To setup a network connection the address or name of remote
machine and a port number is required.
accept() method of ServerSocket class is used in server
program to receive client sockets to establish connection with
the server.
close() method of Socket class is required to close the
connection.
Use Slides 24, 25, and 26 to summarize the session. 14.18 Instructor Inputs ¤NIIT
The following section provides some extra inputs on the important topics covered in the
SG.
Computers running on the Internet communicate with each other by using either the
Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as shown in
the following diagram.
When you write Java programs that can communicate over the network, you are
programming at the application layer. In this case, you need not consider the TCP and
UDP layers. Instead, you can use classes in the java.net package. These classes provide
system-independent network communication. However, to decide which Java classes your
programs should use, you need to understand the difference between TCP and UDP.
TCP
TCP is a connection-based protocol that provides a reliable flow of data between two
computers.
When two applications need to communicate with each other, a connection is established
to send data back and forth over that connection. TCP guarantees that data sent from one
end of the connection actually reaches the other end in the same order it was sent.
Otherwise, an error is reported.
Additional Inputs
Basics of Networking ¤NIIT Instructor Inputs 14.19
UDP
UDP is a protocol that sends independent packets of data, called datagrams, from one
computer to another with no guarantee of arrival.
The UDP protocol provides for communication that is not guaranteed between two
applications on the network. UDP is not a connection-based protocol. It sends
independent packets of data, called datagrams, from one application to another. Sending
datagrams is very similar to sending a letter through the postal service: The order of
delivery is not important but not guaranteed. Each message is independent of any other
message.
Ports
The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer. In general, a computer has a single physical connection to the
network. All data destined for a particular computer arrives through that connection.
However, the data may be intended for different applications running on the computer.
So, how does the computer identify the application to forward the data? The answer is by
using ports.
Data transmitted over the Internet is accompanied by addressing information that
identifies the computer and the port for which it is destined. The computer is identified by
its 32-bit IP address, which the IP uses to deliver data to the right computer on the
network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the
data to the right application.
In a connection-based communication such as TCP, a server application binds a socket to
a specific port number. This registers the server with the system to receive all data
destined for that port. A client can then rendezvous with the server at the server’s port, as
shown in the following diagram.
Socket
A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can
identify the destination application of the data. 14.20 Instructor Inputs ¤NIIT
Normally, a server runs on a specific computer and has a socket that is bound to a specific
port number. The server just waits, listening to the socket for a client to make a
connection request.
The client knows the hostname of the machine on which the server is running and the port
number on which the server is listening. To request for a connection request, the client
tries to rendezvous with the server on the machine and port of the server. The client also
needs to identify itself to the server, so it binds to a local port number that it will use
during this connection. This is usually assigned by the system.
How can you read a line of input at a time?
Ans: To read a line of input at a time, use the readLine method of the BufferedReader
class.
How do you get the IP address of a machine from its hostname?
Ans: The InetAddress class can resolve IP addresses for you. You can obtain an instance
of InetAddress for the machine and call the getHostAddress() method. This returns a
string in the xxx.xxx.xxx.xxx address form.
InetAddress inet = InetAddress.getByName(“www.davidreilly.com”);
System.out.println (“IP : ” + inet.getHostAddress());
FAQs
————————————————————————————————-
