TechAlpine – The Technology world

Creating a Multi-Threaded Server in Java

Java Multi-threading

Java Multi-threading – Creating a Server

Overview:

Java is a very versatile programming language. It can be used to create a powerful server easily. You can create a single server or a single client connection by using Java socket APIs. However, in this article, we will discuss about building a multi-threaded server in Java. We will discuss the techniques which will be required to create the server and we will also know more about multithreading and related concepts. Also, we will learn more about the advantages and the disadvantages of using a multi-threading server in Java. Using multi-threaded server is a very important step in implementing a Compute Server in MapReduce. Thus, we will look at creating a multi-threading server in depth.







What is multi-threading?

Often, the term “multi-threading” is considered to be synonymous with similar sounding terms like “multi-programming” or “multi-tasking”. However, these terms actually have a very different meaning.

Actually, multi-threading defines the capability of a software, an operating system, a process or a hardware component to manage more than one user at one time. Such an application can accept multiple requests by one user without running multiple instances of the program on the computer. Another speciality of such programs is that they record any request of the user as a thread, where the users includes other programs too. Each thread has a special identity so that the application can easily keep track of the commands given to it. As the program is doing the initial work given to it for that thread and is interrupted by any other requests made by other users, it keeps a track of the requests and also the status of work regarding that thread, until the work is completed.

Thus, a thread is nothing but a sub-process which doesn’t take up much system resources. It is the smallest unit of computing. Multi-threading and multi-processing are the main processes of multi-tasking.







However, we use multi-threading more often because it has multiple advantages over multi-processing. The threads in multi-threading have a common area in the computer memory. They do not need separate memory spaces. Thus, they save memory resources of the system. Also, switching contexts take much lesser time in the case of threads than in processes. 

Sockets and threads – Conceptual idea

A socket is an end-point of the connection between two programs running on a network. This end-point is required to establish a communication link between a server program and a client program. These programs run on different computers which are called local and remote computers. But, these two programs can also be run on a single computer.

Actually, the socket links a server program to the port on the computer on which it is running, so any program which is on the network and has the same port for socket can communicate with the server easily. The server actually provides resources for the client programs on the network. The client programs send requests for the services they require to the server program, and the server program responds accordingly.

The easiest and the fastest way of handling these requests is to create a multi-threaded server program. Such a server program creates a thread for every request it receives from the client programs. The thread is a set of instructions which run differently from the program or other such threads. Using this, a server can easily multitask well. It can start a thread for a client and then continue communicating with other programs.


What are the advantages of a multi-threaded server?

The main advantages of using a multi-threaded server over a single-threaded one in Java are given below:

  • It is very quick and doesn’t obstruct the user, as every thread is independent of each other and the program. Thus, the server can respond to many queries at once.
  • As threads are independent of each other, they do not block the work of other threads if exceptions occur in the thread.
  • As it can perform many operations at once, it can save lots of time.
  • Long running requests tend to make single-threaded servers unresponsive, but this is not the case in multi-threaded servers. 

How to write a multi-threaded server?          

Following code is a sample multi-threaded server created by using Java. You can run it and test the output. 

Listing 1: Sample multi-threaded server

[code]

import java.net.ServerSocket;

import java.net.Socket;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.IOException;

import java.net.Socket;

public class MultiThreadedServer implements Runnable{

protected int          serverPort   = 8080;

protected ServerSocket serverSocket = null;

protected boolean      isStopped    = false;

protected Thread       runningThread= null;

public MultiThreadedServer(int port){

this.serverPort = port;

}

public static void main (String[]args)throws IOException

{

//MultiThreadedServer server = new MultiThreadedServer(9000);

MultiThreadedServer server = new MultiThreadedServer(8080);

new Thread(server).start();

try {

Thread.sleep(20 * 1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(“Stopping Server”);

server.stop();

}

public void run(){

synchronized(this){

this.runningThread = Thread.currentThread();

}

System.out.println(“Inside run1”);

openServerSocket();

while(! isStopped()){

Socket clientSocket = null;

try {

System.out.println(“Inside while”);

clientSocket = this.serverSocket.accept();

} catch (IOException e) {

System.out.println(“Inside catch”);

if(isStopped()) {

System.out.println(“Server Stopped.”) ;

return;

}

throw new RuntimeException(

“Error accepting client connection”, e);

}

System.out.println(“calling WorkerRunnable”);

new Thread(

new WorkerRunnable(

clientSocket, “Multithreaded Server”)

).start();

}

System.out.println(“Server Stopped.”) ;

}

private synchronized boolean isStopped() {

return this.isStopped;

}

public synchronized void stop(){

this.isStopped = true;

try {

this.serverSocket.close();

} catch (IOException e) {

throw new RuntimeException(“Error closing server”, e);

}

}

private void openServerSocket() {

try {

System.out.println(“Inside openServerSocket”);

this.serverSocket = new ServerSocket(this.serverPort);

} catch (IOException e) {

throw new RuntimeException(“Cannot open port 8080”, e);

}

}

}

class WorkerRunnable implements Runnable{

protected Socket clientSocket = null;

protected String serverText   = null;

public WorkerRunnable(Socket clientSocket, String serverText) {

this.clientSocket = clientSocket;

this.serverText   = serverText;

}

public void run() {

try {

System.out.println(“Inside Request process”);

InputStream input  = clientSocket.getInputStream();

OutputStream output = clientSocket.getOutputStream();

long time = System.currentTimeMillis();

output.write((“HTTP/1.1 200 OK\n\nWorkerRunnable: ” +

his.serverText + ” – ” +time +””).getBytes());

output.close();

input.close();

System.out.println(“Request processed: ” + time);

} catch (IOException e) {

//report exception somewhere.

e.printStackTrace();

}

}

}

[/code]

What are the disadvantages?

While there are many advantages to multi-threaded programs, there are many disadvantages too. Some of these are given below:

  • Difficult to write: Creating multi-threaded programs are not very easy. Only professionals can do this work nicely.
  • Difficult to debug: Finding the main cause of an error in a multi-threaded program is very difficult.
  • Testing constraints: As the errors in a multi-threaded program are related to timing matters, it is very hard to test compared to a single-threaded program. 



Conclusion:

A multi-threaded server is the need of the hour in this fast going world. Such a server can respond to its client’s queries very quickly and efficiently. However, creating such a server isn’t easy, so this article has discussed all the aspects of creating the server, from major concepts to the process itself. This guide, if followed closely, can easily help you create a good multi-threaded server in Java.

 

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *


4 × 5 =

============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------

Enjoy this blog? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+
http://techalpine.com/creating-a-multi-threaded-server-in-java">
LinkedIn