Wednesday, June 18, 2014


Java Collection Itereator to avoid ConcurrentModificationException getting while iterating the collection and try to remove the element from the collecation:

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. This situation can come in case of multithreaded as well as single threaded environment.

To Avoid ConcurrentModificationException in multi-threaded environment:

1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.

3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

Example:

public void removeRow(){
Iterator it = new CopyOnWriteArrayList(empGroupList).iterator();
while(it.hasNext()) {
EmpGroupData empData = it.next();
if(empData.isSelected()) {
empGroupList.remove(empData);
}
}
for(EmpGroupData empData: empGroupList) {
System.out.println("empno:"+empData.getEmpNo());
}

}

Monday, June 16, 2014

Java Socket Program to Maintain Buffer Queue at server side and provide facilitate to Client

Description: 
To create a Buffere Queue on server side, and client can push the message inside queue, if the queue is full then client will get the message that queue is full.

 Client can receive the inserted message from server and once queue is empty client will get message that queue is empty.

Clint can check the status of the queue, that how much message he inserted in buffer queue.

Server Side Program:


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Administrator
 *
 */
public class BufferQueueServer {

private static int qMaxSize;// max queue size
private static int fp = 0;  // front pointer
private static int rp = 0;  // rear pointer
private static int qs = 0;  // size of queue
private static String[] q;    // actual queue
private static ServerSocket server;

   /**
 * @param size
 * Constructor to initialize the default value of front, rare queue and maximum size of the queue
 */
public BufferQueueServer(int size) {
      qMaxSize = size;
      fp = 0;
      rp = 0;
      qs = 0;
      q = new String[qMaxSize];
      try {
server =new ServerSocket(5050);
} catch (IOException e) {
e.printStackTrace();
}
   }

 

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Waiting for the message from the client....");
BufferQueueServer queue = new BufferQueueServer(4);

while(true) {
try {
//Code to accept the client socket connection
Socket socket = server.accept();
//Create input stream object of server socket
ObjectInputStream FrmClient = new ObjectInputStream(socket.getInputStream());  
//Create output object of client socket
ObjectOutputStream ToClient = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Reading the socket = "+socket);
//Get the input option from client via socket
String str = (String) FrmClient.readObject();
String msg = "";
int option = 0;
//Code to check the option passed by client and if 1 the extract the message which want to add in queue
//else get option directly
if(str.indexOf(",")!=-1) {
String[] msgs=str.split(",");
option = Integer.parseInt(msgs[0]);
msg=msgs[1];
} else {
option = Integer.parseInt(str);
}
System.out.println("Client option is:"+option);
//perform the operation as per the option given by client
switch(option) {
case 1:
System.out.println("Given message is:"+msg);
//Condition to check the queue is full or not, if full then return message else add element in queue
if(!queue.fullq()) {
queue.insert(msg);
ToClient.writeObject("Message added in queue");
} else {
ToClient.writeObject("Queue is full");
}
break;
case 2:
//Condition to check the queue is empty or not, if empty then return message else return the element from queue
if(!queue.emptyq()) {
String recmsg = queue.delete();
ToClient.writeObject("Received msg is:"+recmsg);
} else {
ToClient.writeObject("Queue is empty");
}
break;
case 3:
//Get the queue status and size and return the size of the queue to client
String recmsg = queue.printq();
ToClient.writeObject("Received msg is:"+recmsg);
break;
}
socket.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* @return
* Method to delete the element from the queue and return to first element input by queue
*/
public String delete() {
     if (!emptyq()) {
        qs--;
        fp = (fp)%qMaxSize;
        return q[fp++];
     }
     else {
        System.err.println("Underflow");
        return "?";
     }
  }

/**
* @param c
* Method to insert the element in queue
*/
public void insert(String c) {
     if (!fullq()) {
        qs++;
        rp = (rp)%qMaxSize;
        q[rp] = c;
        rp++;
     }
     else
        System.err.println("Overflow\n");
  }

/**
* @return
* Method to check for empty queue
*/
public boolean emptyq() {
     return qs == 0;
  }

/**
* @return
* Method to check for full queue
*/
public boolean fullq() {
     return qs == qMaxSize;
  }
 
/**
* @return
* Method to print the total number of element inside queue+
*/
public String printq() {
    return "Total size of queue is:"+qs+"\n";
  }

}


Client Side Program

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author Administrator
 * Client class to add, retrieve and check the status of the queue from server
 *
 */
public class BufferQueueClient {

public static void main(String[] args) {
try {
String flagCont = "y";
//Flag to check continue message
while("y".equalsIgnoreCase(flagCont)) {              
                int check=1,choice=0;
                //Flag to select the option for the operation
                while(check==1){
                    try{
                    System.out.println("\n\nChoose following option.\n1. For add message\n2. For receive message.\n3. Check Status of queue.\n");
                        Scanner sc=new Scanner(System.in);
                        choice=sc.nextInt();
                        if(choice == 1 || choice == 2 || choice == 3)
                        check=0;
                        else {
                        System.out.println("Please enter correct choice.");
                            check=1;
                        }
                    }
                    catch(Exception e){
                        System.out.println("Please input your choice as a number.");
                        check=1;
                    }
                }
                //Code to open socket connection
                Socket socket = new Socket("localhost", 5050);
                //Create output stream of connected socket
    ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());
    //Create input stream of connected socket
                ObjectInputStream fromServer = new ObjectInputStream(socket.getInputStream());
                System.out.println("Clent is connected with server");
                String msg = "";
                Scanner sc=new Scanner(System.in);
                /**Switch statement to pass the option to server and get the service
                 * 1. To add the message in server queue
                 * 2. To get the message from queue from server
                 * 3. Check the status of the queue
                 */
               
switch(choice) {
case 1:
System.out.println("Please enter message to add in queue.");
            msg = sc.nextLine();
            toServer.writeObject("1,"+msg);
            msg=(String)fromServer.readObject();
            System.out.println(msg);
break;
case 2:
 toServer.writeObject("2");
 msg=(String)fromServer.readObject();
         System.out.println(msg);
break;
case 3:
 toServer.writeObject("3");
 msg=(String)fromServer.readObject();
         System.out.println(msg);
break;
default:
System.out.println("Invalid choice.Please enter the correct choice");
}
System.out.println("Do you want to continue? Press Y for yes and N for no");
flagCont=sc.nextLine();
                 toServer.close();
                 fromServer.close();
         }


} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


}