How to implement read and write method in multithreading socket connection
<p>I have a program which reads and writes data from a LIS machine. I am reading data from a specific port and writing data to a database table. When I read data from a table and adding them into an Arraylist, it is adding duplicate record. I could not find the solution.</p>

<p>The code is following:</p>

<pre><code>public class PacsMultiThread extends Thread{

    private static Logger logger = Logger.getLogger(PacsMultiThread.class);

    // instance for Server socket and Socket class
    private ServerSocket serverSocket = null;
    private Socket socket = null;  
    ServerParams params = Configuration.getConfig().getServerParams();

    PacsMultiThread() {

        super("PacsMultiThread");

        try {
            // listen on local port
            serverSocket = new ServerSocket(Configuration.getConfig().getHostParams().getPort());

        } catch (IOException e) {
            logger.error("Could not listen on port: " + Configuration.getConfig().getServerParams().getPort() + ", " + e);
            System.exit(1);
        }
    }

    /*
     * thread run method call
     * @see java.lang.Thread#run()
     * Mohammod Hossain
     */
     public void run() {

         logger.info("run method is calling... ");

            if (serverSocket == null)
                return;

            while (true) {              
                try {
                    socket = serverSocket.accept();
                     logger.info("connection status: "+ socket.isConnected());
                } catch (IOException e) {
                    logger.error("Accept failed: " + Configuration.getConfig().getServerParams().getPort() + ", " + e);
                    System.exit(1);
                }           

                    try {
                        // readData();
                        //calling new Thread for reading data from port
                        ReadHandler readThread = new ReadHandler(socket);
                        readThread.start();

                       // writeData(socket);

                        //calling new Thread for writing  data into port
                        WriteHandler writeThread = new WriteHandler(socket);
                        writeThread.start();

                      } catch (Exception e) {
                          logger.error(e.getMessage());
                        }         
            }
        }




    public class WriteHandler extends Thread {
         private static Logger logger = Logger.getLogger(WriteHandler.class);
        private Socket socket;

    ServerParams params = Configuration.getConfig().getServerParams();
    OutputStream out = null;

    public WriteHandler(Socket socketConnection){
        super();
        this.socket = socketConnection;
    }

    @Override
    public void run() {

        writeData(socket);
    }

    private void writeData(Socket socket){

         /*
          * calling  writeData method for data write to port
          * @param Socket socket
          */

         logger.info("writeData method is called :: ");      

          try{ 
              //calling client socket method for connect to server port
             // logger.info(" client socket "+socket.getRemoteSocketAddress());  
              // check data exist in table in HL7001;

                List&lt;HL7001&gt; orderList = new ArrayList&lt;HL7001&gt;();
                PacsDao pacsDao = new PacsDao();
                orderList = pacsDao.getAllOrder();              

                //PrintWriter pw = new PrintWriter(theOutput, false);   
                int msgCount = 0;

                if(orderList.size() &gt; 0){   

                    for(int i = 0;i&lt;orderList.size();i++){

                    logger.info("orderList.size(): " + orderList.size());

                    HL7001 model = orderList.get(i);

                    logger.info("message from HL7001 Table :: " +"Msg Order No: "+
                            model.getOrderNo() +"\n"+" msg no:"+ model.getHl7MsgNo()+"\n"+" message: "+model.getHl7Msg());


                    //for(HL7001 model:orderList){                  
                    String tableMessage = model.getHl7Msg();

                    // read ADT Message from Table HL7001;

                    //readADTMsg(tableMessage);

                    // logging TABLE MESSAGE  data into file


                        StringBuffer transmitMsg =  new StringBuffer();
                        transmitMsg
                        .append(START_OF_BLOCK)
                        .append(tableMessage)
                        .append(END_OF_BLOCK)
                        .append(CARRAIGE_RETURN);

                        // write data to port

                         socket = new Socket(Configuration.getConfig().getServerParams().getUrl(), Configuration.getConfig().getServerParams().getPort());

                         if(socket.isConnected()){ 
                             logger.info(socket.getRemoteSocketAddress()+" port is connected ");
                             HL7007 hl7007 = new HL7007();
                             hl7007.setMsgNo(model.getHl7MsgNo());
                             hl7007.setPortAdress(socket.getRemoteSocketAddress().toString() );
                             opeonSocketLog(hl7007);
                         }else{
                             logger.error("Server socket is not conneted");
                         }
                        out = socket.getOutputStream();
                        //InputStream in =  socket.getInputStream();
                        out.write(transmitMsg.toString().getBytes());

                        // save file into directory             

                        // logging TABLE MESSAGE  data into file
                        if (params.isOutputOnFile()) {
                            //comment this line for performance issue

                            FileLogger.log2(transmitMsg.toString());
                        }

                      /** Write across the socket connection and flush the buffer */

                        out.flush();                                            
                        out.close();                        
                        // insert into record from Table HL7001 to  Table HL7003;


                        insertOrderModel(model);                        

                        msgCount++; 

                        logger.info("msgCount "+ msgCount);                     

                        if (Configuration.getConfig().getServerParams().getWaitingOption().equals("1")) {
                            try{
                                 Thread.sleep(1000);                            

                             }catch (InterruptedException e) {
                                logger.error("Wait for writing message into "+ e.getMessage());
                            }
                        }           
                }               

                    }           

          }catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }finally{
                try {
                    logger.info("finally block is executed in write method ");
                    socket.close();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }
     }
</code></pre>

<p>In the above write class  at first I read records from a table , then adding into list . If record exists I am open a socket connection then write data into port and delete the following record. But  sometimes I am getting more  duplicate records </p>
