Friday, August 22, 2014

Multithreading and Multiplexing

Thread Basics

A thread is a fl ow of control through a program.

Unlike a process, a thread does not have a separate allocation of memory, but shares memory with other threads created by the same application.

Threads created by an application can share global variables.

We cannot avoid using threads in Java, since each program will have at least one thread that is launched automatically by our machine’s JVM when that program is executed.

Which thread is given to the processor depends on
• Thread priority (1–10, in increasing order of importance) in Java.
• Whether scheduling is pre-emptive or cooperative.

A pre-emptive scheduler will determine when a thread has had its fair share of CPU time (possibly via simple time allocation) and will then pause it (temporarily).

A cooperative scheduler, on the other hand, will wait for the running thread to pause itself before giving control of the CPU to another thread. A JVM using cooperative scheduling is thus much more susceptible to thread starvation.

On PCs, threads with the same priority are each given an equal time-slice or time quantum for execution on the processor.

When the quantum expires, the first thread is suspended and the next thread in the queue is given the processor, and so on. If some threads require more urgent attention than others, then they may be assigned
higher priorities (allowing pre-emption to occur).

Using Threads in Java

The run method specifies the actions that a thread is to execute and serves the same purpose for the process running on the thread as method main does for a full application program.

Like main , run may not be called directly. The containing program calls the start method (inherited from class Thread ), which then automatically calls run.


In practice, of course, different threads will normally carry out different tasks.

If we want the threads to carry out actions different from each other’s, then we must create a separate class for each thread (each with its own run method)

Multithreaded Servers

There are two possible solutions:

  •  use a non-blocking server
  •  use a multithreaded server
Multithreaded server


The basic technique involves a two-stage process:
1. the main thread (the one running automatically in method main ) allocates individual threads to incoming clients;
2. the thread allocated to each individual client then handles all subsequent interaction between that client and the server (via the thread’s run method).

import java.io.*;
import java.net.*;

public class MultiEchoServer {
private static ServerSocket serverSocket;
private static final int PORT = 1234;

public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ioEx) {
System.out.println("\nUnable to set up port!");
System.exit(1);
}
do {
// Wait for client…
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
// Create a thread to handle communication with
// this client and pass the constructor for this
// thread a reference to the relevant socket…
ClientHandler handler = new ClientHandler(client);
handler.start();// As usual, method calls run .
} while (true);
}
}

class ClientHandler extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;

public ClientHandler(Socket socket) {
// Set up reference to associated socket…
client = socket;
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}

public void run() {
String received;
do {
// Accept message from client on
// the socket's input stream…
received = input.nextLine();
// Echo message back to client on
// the socket's output stream…
output.println("ECHO: " + received);
// Repeat above until 'QUIT' sent by client…
} while (!received.equals("QUIT"));
try {
if (client != null) {
System.out.println("Closing down connection…");
client.close();
}
} catch (IOException ioEx) {
System.out.println("Unable to disconnect!");
}
}
}

Locks and Deadlock

Data Integrity requires locking and the side effect of locking is deadlock

Any other (updating) thread must wait until the lock has been released. Once the fi rst thread has fi nished its updating, it should release the lock, making it available to other such threads.

Threads requiring read-only access do not need to obtain a lock.







Thursday, August 21, 2014

Starting Network Programming in Java

The InetAddress Class

InetAddress address = InetAddress.getByName(host);

InetAddress address = InetAddress.getLocalHost();

TCP Sockets

A communication link created via TCP/IP sockets is a connection-orientated link.

This means that the connection between server and client remains open throughout the duration of the dialogue between the two and is only broken (under normal circumstances) when one end of the dialogue formally terminates the exchanges.

Server
ServerSocket serverSocket = new ServerSocket(1234);
Socket link = serverSocket.accept();

Scanner input = new Scanner(link.getInputStream());
String input = input.nextLine();

//true will cause the output buffer to be fl ushed for every call of println
PrintWriter output = new PrintWriter(link.getOutputStream(),true);

link.close();

Client
Socket link = new Socket(InetAddress.getLocalHost(),1234);
Scanner input = new Scanner(link.getInputStream());

PrintWriter output = new PrintWriter(link.getOutputStream(),true);
Scanner userEntry = new Scanner(System.in);
String message = userEntry.nextLine();

Datagram (UDP) Sockets

Server

DatagramSocket datagramSocket = new DatagramSocket(1234);

byte[] buffer = new byte[256];
DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);

datagramSocket.receive(inPacket);

InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();

String message = new String(inPacket.getData(),0,inPacket.getLength());

DatagramPacket outPacket = new DatagramPacket(response.getBytes(), response.length(),clientAddress, clientPort);

datagramSocket.send(outPacket);

Client

DatagramSocket datagramSocket = new DatagramSocket();

DatagramPacket outPacket = new DatagramPacket(message.getBytes(), message.length(), host, PORT);

datagramSocket.send(outPacket);

byte[] buffer = new byte[256];

DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);

datagramSocket.receive(inPacket);

Basics concepts, Protocols and Terminology

Machine on which the server is running is called the host machine.

In some applications, such as messaging services, it is possible for programs on users’ machines to communicate directly with each other in what is called peer-to peer (or P2P ) mode. However, for many applications, this is either not possible or prohibitively costly in terms of the number of simultaneous connections required.

Ports and Sockets
A port is a logical connection to a computer and is identifi ed by a number in the range 1–65535.

Ports are implemented upon all computers attached to a network, but it is only those machines that have server programs running on them for which the network programmer will refer explicitly to port numbers.

Port numbers in the range 1–1023 are normally set aside for the use of specifi ed standard services, often referred to as ‘well-known’ services.

The server needs some way of distinguishing between clients and keeping their dialogues separate from each other. This is achieved via the use of sockets.

When a client wishes to make connection to a server, it will create a socket at its end of the communication link. Upon receiving the client’s initial request (on a particular port number), the server will create a new socket at its end that will be dedicated to communication with that particular client.

Just as one hardware link to a server may be associated with many ports, so too may one port be
associated with many sockets.

The Internet and IP Addresses

The protocol used for such communication is called the Internet Protocol (IP). The Internet (upper-case ‘I’) is the world’s largest IP-based network.

IPV4 address machine addresses in what is called quad notation. This is made up of four eight-bit numbers i.e., numbers in the decimal range 0–255), separated by dots.

IPv6 uses 128-bit addresses, which provide massively more addresses.

URL
<protocol>://<hostname>[:<port>][/<pathname>] [/<fi lename>[#<section>]]

TCP

The Internet is a packet-switched network.

Each packet being handled separately and possibly travelling by a completely different route from that of others.

IP is concerned with the routing of these packets through an internet.

It attaches the IP address of the intended recipient to each packet and then tries to determine the most effi cient route available to get to the ultimate destination (taking damaged routers into account).

However, since packets could still arrive out of sequence, be corrupted or even not arrive at all (without indication to either sender or intended recipient that anything had gone wrong), it was decided to place another protocol layer on top of IP.

This further layer was provided by TCP (Transmission Control Protocol), which allowed each end of a connection to acknowledge receipt of IP packets and/or request re-transmission of lost or corrupted packets.

In addition, TCP allows the packets to be rearranged into their correct sequence at the receiving end.

For the TCP layer, this process involves breaking up the data packets into TCP segments and adding sequence numbers and checksums; for the IP layer, it involves placing the TCP segments into IP packets called datagrams and adding the routing details.

If recalculation of checksums reveals that some of the data has been corrupted or checking of sequence numbers shows that some data has not been received, then the transport layer requests re-transmission of the corrupt/missing data. Otherwise, the transport layer acknowledges receipt of the packets.

TCP provides full duplex transmission, the two ends of the connection may be sending data simultaneously.

UDP

User Datagram Protocol (UDP) is an unreliable protocol, since:

i) it doesn’t guarantee that each packet of data will arrive;
(ii) it doesn’t guarantee that packets will be in the right order.

UDP doesn’t re-send a packet if it fails to arrive or there is some other error and it doesn’t re-assemble packets into the correct sequence at the receiving end.

TCP overhead of providing facilities such as confirmation of receipt and re-transmission of lost or corrupted packets used to mean that UDP was significantly faster than TCP.