Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Suddenly getting "Too Many Open File" error

  1. #1
    Junior Member
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Suddenly getting "Too Many Open File" error

    Dear All,
    I have java listener which keep reading for incoming data to the particular port. Most of the times it works fine only at times it gets too many open files error. Below is my codes what could be wrong? Thank you.


    public static void main(String[] args) {
     
     try 
     {
       final ServerSocket serverSocketConn = new ServerSocket(8888);
     
     
       while (true) 
       {
        try 
        {
           Socket socketConn1 = serverSocketConn.accept();
           new Thread(new ConnectionHandler(socketConn1)).start(); 
        }
       catch(Exception e)
       {
          System.out.println(e.toString());
        }
      }
     
     
      } 
      catch (Exception e) 
      {
      System.out.println(e.toString());
      //System.exit(0); 
      }
    }
     
     
    }
    class ConnectionHandler implements Runnable 
    {
       private Socket receivedSocketConn1;
       DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
       DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy"); 
       DateFormat inDf=new SimpleDateFormat("ddMMyyHHmmss"); 
       DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     
       ConnectionHandler(Socket receivedSocketConn1) 
       {
       this.receivedSocketConn1=receivedSocketConn1;
       }
     
    //@Override
    public void run() 
    { 
          Connection dbconn = null;
          BufferedWriter w = null;
          BufferedReader r = null;
     try 
     {
     
     
             PrintStream out = System.out; 
             BufferedWriter fout = null;
             w = new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
             r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
     
             int m = 0, count=0;
             String line="";
             String n="";
             w.write("$PA\n");
             w.flush();
                 while ((m=r.read()) != -1) 
                 {
                      Date dateIn = new Date();
                      n = n + (char) m;
                      int i = n.indexOf("GET");
                      if(i != -1) 
                      { 
                         break;
                      }
     
     
                     if (m==35)
                     {
     
     
                       String ori = n;
                       String noCheckSum = n.substring(0,(n.length()-4));
                       int addExist = n.indexOf("@");
     
                       String[] slave = null;
                       if(addExist!=-1)
                       {
                         slave = noCheckSum.split("@");
                         n = slave[0];
                       }
                       else
                       {
                         n = noCheckSum;
                       }
     
                       String[] result = n.split(",");
                       Statement stmt = null;
     
                       w.write("$PA\n");
                       w.flush();
     
                       int count1 = 0;
     
                       Date date = Calendar.getInstance().getTime(); 
                       String today = formatter.format(date); 
                       String filename= "MyDataFile"today".txt"; 
                       boolean append = true; 
     
     
                       FileWriter fw = null;
                       try
                       {
                        fw = new FileWriter(filename,append); 
                        fw.write(ori+" "dateFormat.format(dateIn)"\n");//appends the string to the file 
                        Date dateOut = new Date();
                        fw.write("$PA"+" "dateFormat.format(dateOut)"\n");//appends the string to the file 
                       }
                       catch (IOException ex) 
                       { 
                       System.out.println("MyError:IOException has been caught in in the file operation");
                       ex.printStackTrace();
                       } 
                      finally
                      {
                        try 
                        {
                         if ( fw != null ) 
                         {
                           fw.close();
                         }
                         else 
                         {
                           System.out.println("MyError:fw is null in finally close");
                         }
                      }
                      catch(IOException ex){
                          System.out.println("MyError:IOException has been caught in fw is null in finally close");
                          ex.printStackTrace();
                      }
                  }
                  try
                  {
     
     
                   String deviceID=result[3].trim(); 
                   String dateTime=result[4].trim(); 
                   String[] result2 = result[10].split("'"); 
                   String gpsDate = result2[1].trim().substring(0,6); 
                   String gpsTime = result2[1].trim().substring(6,12); 
                   String gpsLat = result2[1].trim().substring(13,20);
                   String latitude = result2[1].trim().substring(13,20).substring(0,2)+"."+result2[1].trim().substring(13,20).substring(2,7);
                   String gpsLong = result2[1].trim().substring(21,29);
                   String longitude = result2[1].trim().substring(21,29).substring(0,3)+"."+result2[1].trim().substring(21,29).substring(3,8);
                   String speed = result2[1].trim().substring(30,33); 
                   String course = result2[1].trim().substring(33,36);
                   String dateTimer = null;
                   try
                   { 
                       Date inDate=null; 
                       inDf.setTimeZone(TimeZone.getTimeZone("UTC")); 
                       inDate=inDf.parse(dateTime); 
                       outDf.setTimeZone(TimeZone.getTimeZone("Asia/Kuala_Lumpur")); 
                       dateTimer=outDf.format(inDate); 
                   }
                      catch(ParseException ex)
                   { 
                       System.out.println("MyError:Parse Error has been caught for date parse close");
                       ex.printStackTrace();
                   } 
     
                   dbconn = DriverManager.getConnection("jdbc:mysql://192.168.1.155:3306/db1?"+"user=db1&password=test1");
                   stmt = dbconn.createStatement();
     
                   String selectQuery2 = "Select * from tripData Where deviceID='"+ deviceID +"' and dateTimer>'"dateTimer"' Order By dateTimer Desc Limit 1"; 
                   ResultSet rs2 = stmt.executeQuery(selectQuery2);
     
     
                   String updateQuery = "";
                   if(rs2.next())
                   {
                      String previousLatitude="";
                      String previousLongitude="";
                      String previousSpeed="";
     
                      previousLatitude = rs2.getString("latitude");
                      previousLongitude = rs2.getString("longitude");
                      previousSpeed = rs2.getString("speed");
     
                      updateQuery = "UPDATE device SET " + 
                      "latitude='" + previousLatitude + 
                       "',longitude='" + previousLongitude + 
                       "',speed='" + previousSpeed + 
                       "' WHERE serialNumber='" + deviceID + "'";
                   }
                   else
                   {
     
     
                      updateQuery = "UPDATE device SET " + 
                       "latitude='" + latitude + 
                       "',longitude='" + longitude + 
                       "',speed='" + speed + 
                       "',course='" + course +
                       "',dateTimer='" + dateTimer +
                       "' WHERE serialNumber='" + deviceID + "'";
                    } 
                    count = stmt.executeUpdate(updateQuery); 
     
     
                    String insertQuery = "INSERT INTO tripData" + 
                     "(latitude,longitude,speed,course,dateTimer,deviceID)" + " VALUES ('" + 
                     latitude + "','" + longitude + "','" + speed + "','" + course + "','" + dateTimer + "','" + deviceID + "' )";
                    count = stmt.executeUpdate(insertQuery);
     
     
                   if(addExist!=-1)
                   {
                     for(int iSlave=1; iSlave<slave.length ; iSlave++)
                     {
                        String[] slaveDetails = slave[iSlave].split(",",-1);
                        String slaveEventType = slaveDetails[0];
                        String slaveGroup = slaveDetails[1];
                        String slaveUnitID = slaveDetails[2];
                        String slaveBattLevel = slaveDetails[3];
                        String slaveSwitchStat = slaveDetails[4];
                        String slaveTempHumid = slaveDetails[5];
                        String slaveTemp="",slaveHumid=""; 
                        if(slaveTempHumid.length()>0)
                         {
                          slaveHumid = slaveTempHumid.substring(5,7);
                          if(slaveTempHumid.charAt(0)=='P')
                          {
                            slaveTemp = "+"slaveTempHumid.substring(1,3)"."+slaveTempHumid.substring(3,5); 
                          }
                          else if(slaveTempHumid.charAt(0)=='M')
                          {
                            slaveTemp = "-"slaveTempHumid.substring(1,3)"."+slaveTempHumid.substring(3,5);
                           }
                         }
                        slaveBattLevel = slaveBattLevel.trim().substring(0,2)+"."+slaveBattLevel.trim().substring(2,3);
                        String insertQuery2 = "INSERT INTO tripDataSlave" + 
                         "(dateTimer,deviceID,slaveUnitID,slaveEventType,slaveGroup,slaveBattLevel,slaveSwitchStat,slaveTemp                     ,slaveHumidity)" + " VALUES ('" + dateTimer + "','" + deviceID + "','" + slaveUnitID + "','" +   slaveEventType + "','" + slaveGroup + "','" + slaveBattLevel + "','" + slaveSwitchStat + "','" + slaveTemp + "','" +  slaveHumid + "')";
                        count = stmt.executeUpdate(insertQuery2);
                      }
                   }
                }
               catch (SQLException ex) 
               { 
                System.out.println("MyError:Error : "+ex);
     
               } 
               finally
              {
               try 
               {
                  if ( stmt != null ) 
                  {
                   stmt.close();
                  }
                  else 
                  {
                    System.out.println("MyError:stmt is null in finally close");
                  }
                }
                catch(SQLException ex){
                      System.out.println("MyError:SQLException has been caught for stmt close");
                      ex.printStackTrace();
                }
                try 
                {
                 if ( dbconn != null ) 
                 {
                   dbconn.close();
                 }
                  else 
                 {
                    System.out.println("MyError:dbconn is null in finally close");
                  }
                }
                catch(SQLException ex){
                     System.out.println("MyError:SQLException has been caught for dbconn close");
                     ex.printStackTrace();
                }
     
     
          }
           n="";
         }
      }
     } 
     catch (IOException ex) 
     { 
     System.out.println("MyError:IOException has been caught in in the main first try");
     ex.printStackTrace();
     } 
     finally
     {
       try 
       {
        if ( w != null ) 
        {
          w.close();
        }
        else 
        {
         System.out.println("MyError:w is null in finally close");
        }
       }
        catch(IOException ex){
         System.out.println("MyError:IOException has been caught in w in finally close");
        ex.printStackTrace();
       }
     
      }
     }
    }


  2. #2
    Junior Member
    Join Date
    Nov 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Suddenly getting "Too Many Open File" error

    You keep declaring a new Socket.

  3. #3
    Junior Member
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Suddenly getting "Too Many Open File" error

    Dear Friend,
    Can you tell me what is the solution? Thank you.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Suddenly getting "Too Many Open File" error

    while (true) 
       {
        try 
        {
           Socket socketConn1 = serverSocketConn.accept();
           new Thread(new ConnectionHandler(socketConn1)).start(); 
        }
       catch(Exception e)
       {
          System.out.println(e.toString());
        }
      }
    This will repeat forever, creating more and more sockets.

    I suspect you only want to open the socket once, simply remove it from the while(true) loop.

  5. #5
    Junior Member
    Join Date
    Dec 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Suddenly getting "Too Many Open File" error

    Dear Helloworld,
    No the problem is this listener will keep listening for new incoming data. So that is why I left in a while loop? Thank you.

Similar Threads

  1. Replies: 6
    Last Post: November 12th, 2010, 03:40 AM
  2. Replies: 1
    Last Post: March 31st, 2010, 09:42 PM
  3. Replies: 1
    Last Post: January 15th, 2010, 12:32 AM
  4. "java.lang.NoSuchMethodError: main" and "fatal exception occured."
    By joachim89 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 10th, 2010, 07:35 AM
  5. Replies: 4
    Last Post: June 18th, 2009, 09:23 AM