0

I have created an application using java swing in where a timer is scheduled to save the scanned tags in an RFID reader into db each second and display it the active tag in the jtable to what time it was been seen.Currenly using FileWriter The application needs to continously run. FileWriter writer = new FileWriter("text.txt", true); // this is to save the tags into a text file aside from saving the tags in the database.

I have tried using the the answers in the previous post here like flushing the writer, closing it and calling garbage collector in runtime.

as you can see from the image, the application has consumed 1.2gb of memory which is the real issue.

The problem is it gives me a heap space out of memory error within 12 hours and there is no backtrace for it for me to see where the leak is coming from. Is there a way to delete the collected garbage from JVM to keep the memory free?

The behavior of the application is that by time passess, it's consuption to physical memory of PC get's larger and larger. which results to heap space overload.

Currently using eclipse Neon

this is the rfid reader

Code from RfidReader Class

    public class RfidTagSearch{
        public String getReaderResult() {return inputReader.toString();}
        public String getResult() {return res;}
        public String getTags() {return strBuff.toString();}
        public String getStrResult() {return strResult.toString();}


        public ArrayList<String> getSeenKey(){
            ArrayList<String> temp = rfidKey;
            rfidKey.clear();
            return temp;
        }



        public void connectToReader(String host, int _port) throws Exception{

            hostName = host;
            port = _port;
            myReader.Dispose();
            myReader = new RFIDReader();

            myReader.setHostName(hostName);
            myReader.setPort(port);

            try {

                myReader.connect();

                myReader.Events.setInventoryStartEvent(true);
                myReader.Events.setInventoryStopEvent(true);
                myReader.Events.setAccessStartEvent(true);
                myReader.Events.setAccessStopEvent(true);
                myReader.Events.setAntennaEvent(true);
                myReader.Events.setGPIEvent(true);
                myReader.Events.setBufferFullEvent(true);
                myReader.Events.setBufferFullWarningEvent(true);
                myReader.Events.setReaderDisconnectEvent(true);
                myReader.Events.setReaderExceptionEvent(true);
                myReader.Events.setTagReadEvent(true);
                myReader.Events.setAttachTagDataWithReadEvent(false);

                            TagStorageSettings tagStorageSettings = myReader.Config.getTagStorageSettings();
                            tagStorageSettings.discardTagsOnInventoryStop(true);
                            myReader.Config.setTagStorageSettings(tagStorageSettings);

                myReader.Events.addEventsListener(new EventsHandler());

                isConnected = true;
                strResult.append("Connected to " + hostName + "\n");
                //strResult.append(API_SUCCESS);
                myReader.Config.setTraceLevel(TRACE_LEVEL.TRACE_LEVEL_ERROR);
                res = "Success";

            } catch (InvalidUsageException ex)
                    {
                strResult.append(PARAM_ERROR +  ex.getVendorMessage());
            } catch (OperationFailureException ex) {
                strResult.append(ex.getStatusDescription() +
                        ex.getVendorMessage());
            }

        }

        public Boolean isConnected() { return isConnected;}

        public void disconnectToReader() throws Exception{

            myReader = new RFIDReader();

        }

        private Boolean isScanning = false;
        // start Scanning
        public void startScanning() throws InterruptedException,InvalidUsageException,OperationFailureException
        {
               tagStore.clear();
               myReader.Actions.Inventory.perform();     
        }

        public void stopScanning() throws InvalidUsageException, OperationFailureException, InterruptedException{

            myReader.Actions.Inventory.stop();

        }

        String saveDir = "", fileName = "";

        public void setSaveDirectory(String value) {
            saveDir = value;
        }

        public long getTagCount() {return totalTags;}

        // getting current time and date
            public String getDateandTime(){
                String res = "";
                LocalDateTime myDateObj = LocalDateTime.now();
                DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDate = myDateObj.format(myFormatObj);

                res = formattedDate.toString();
                return res;
            }

            int Switch=0,tempVal=0;

            public void setTimer(int minute){

                long timeInterval = minute * 60 * 1000;
                timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                      @Override
                      public void run() {

                          Switch++;

                      }
                    }, timeInterval, timeInterval);


            }


        FileWriter fw;

        public class EventsHandler implements RfidEventsListener
        {
            public EventsHandler()
            {
                fileName = getDateandTime().replace(":", "-") + ".txt"; 
            }



             public void eventReadNotify(RfidReadEvents e){

                 TagDataArray oTagDataArray = myReader.Actions.getReadTagsEx(1000);
                    myTags = oTagDataArray.getTags();

                    try {
                     fw = new FileWriter(saveDir + "/" + fileName,true);                    
                        if (myTags != null)
                        {

                            for (int index = 0; index < oTagDataArray.getLength(); index++) 
                             {
                                 if (Switch != tempVal) {
                                     tempVal = Switch;
                                     fileName = getDateandTime().replace(":", "-") + ".txt";
                                     fw = new FileWriter(saveDir + "/" + fileName,true);
                                 }

                                 TagData tag = myTags[index];
                                 String key = tag.getTagID();

                                 String subStr = key.substring(key.length() - 6,key.length());

                                 res = mysql.validateRfidKey(subStr);
                                 if (res.equals("Found")){
                                     res = mysql.updateLastSeen(subStr, getDateandTime());
                                     res = mysql.searchAllData(subStr);
                                     if (res.equals("Found")){
                                         if (mysql.getStatus().equals("1")){
                                             rfidKey.add(subStr);
                                             key = key + " - THIS KEY IS FOUND";
                                         }                                   
                                     }
                                 }
                                 else{
                                     res = mysql.searchUnregisteredKey(subStr);
                                     if (res.equals("Found")) {
                                         key = key + " - UNREGISTERED KEY";

                                     }
                                     else {
                                         key = key + " -NEW UNREGISTERED KEY";
                                         res = mysql.saveUnregisteredKey(subStr, getDateandTime());                                  
                                     }
                                 }                               

                                 fw.write(getDateandTime() +" : "+ key + System.getProperty( "line.separator")); // THE DATA OF THE READER WILL BE INPUTTED HERE AND WILL BE SAVE TO LOCAL PC                       
                                 totalTags++;

                             }



                        }
                        else {
                            fw.write("empty tag");;
                        }

                        fw.flush();

                        fw.close();
                        System.gc();
                        Runtime.getRuntime().gc();



                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        System.out.print("Error in RFID tag search");
                        e1.printStackTrace();
                    }    

                }

                // Status Event Notification

                public void eventStatusNotify(RfidStatusEvents e) {

                    System.out.println("Status Notification " + e.StatusEventData.getStatusEventType());

                }
        }

    } 

Code from JTable

    public class RFIDReaderClient extends JFrame {

        private JPanel contentPane;
        private JTextField txtIP;
        private JTextField txtPort;
        private JTextField txtTimeInterval;
        private JTextField txtSaveDir;
        private JTable ResTable;
         Object[] columns = {"Stock Number","RFID Number","Date Last Seen","Date Removed","Vehicle Year","Color","Model"};
         DefaultTableModel model = new DefaultTableModel();
         DefaultTableModel model1 = new DefaultTableModel();

         private JButton btnAdminPanel;
         private JLabel lblLost;
         private JTextField textField_4;
         private JButton btnConnect;
         private JButton btnStart;
         private JButton btnStop;
         private JLabel label;
         private JLabel lbStatus;
         Timer timer;
         RfidTagSearch rfid;


         SQLConnection mysql;
         Connection connection;
         private JTable tblResult;

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        RFIDReaderClient frame = new RFIDReaderClient();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public void setTable(){
             model  = new DefaultTableModel() {
                    @Override
                    public boolean isCellEditable(int row, int column) {
                       //all cells false
                       return false;
                    }
            };

             model1  = new DefaultTableModel() {
                    @Override
                    public boolean isCellEditable(int row, int column) {
                       //all cells false
                       return false;
                    }
            };


             model.setColumnIdentifiers(columns);
             ResTable.setModel(model);

                ResTable.setBackground(Color.LIGHT_GRAY);
                ResTable.setForeground(Color.black);
                Font font = new Font("",1,22);
                ResTable.setFont(font);
                ResTable.setRowHeight(30);

                 model1.setColumnIdentifiers(columns);
                 tblResult.setModel(model1);

                 tblResult.setBackground(Color.LIGHT_GRAY);
                 tblResult.setForeground(Color.black);
                    font = new Font("",1,22);
                    tblResult.setFont(font);
                    tblResult.setRowHeight(30);


        }

        public RFIDReaderClient() {
            setTitle("RFID Reader");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 1245, 759);
            contentPane = new JPanel();
            contentPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
            setContentPane(contentPane);
            contentPane.setLayout(null);
            mysql = new SQLConnection();
            try {
                connection = mysql.connectDB();
            } catch (ClassNotFoundException | SQLException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }

            JLabel lblIp = new JLabel("IP");
            lblIp.setFont(new Font("Tekton Pro Cond", Font.BOLD, 16));
            lblIp.setBounds(20, 11, 50, 22);
            contentPane.add(lblIp);

            JLabel lblPort = new JLabel("Port");
            lblPort.setFont(new Font("Tekton Pro Cond", Font.BOLD, 16));
            lblPort.setBounds(186, 11, 50, 22);
            contentPane.add(lblPort);

            JLabel lblTimeIntervalminutes = new JLabel("Time Interval (Minutes)");
            lblTimeIntervalminutes.setFont(new Font("Tekton Pro Cond", Font.BOLD, 16));
            lblTimeIntervalminutes.setBounds(268, 11, 248, 22);
            contentPane.add(lblTimeIntervalminutes);

            JLabel lblSaveDirectory = new JLabel("Save Directory");
            lblSaveDirectory.setFont(new Font("Tekton Pro Cond", Font.BOLD, 16));
            lblSaveDirectory.setBounds(20, 67, 137, 22);
            contentPane.add(lblSaveDirectory);

            txtIP = new JTextField();
            txtIP.setEditable(false);
            txtIP.setText("169.254.10.1");
            txtIP.setBounds(20, 34, 151, 22);
            contentPane.add(txtIP);
            txtIP.setColumns(10);

            txtPort = new JTextField();
            txtPort.setEditable(false);
            txtPort.setText("5084");
            txtPort.setColumns(10);
            txtPort.setBounds(186, 35, 72, 22);
            contentPane.add(txtPort);

            txtTimeInterval = new JTextField();
            txtTimeInterval.setColumns(10);
            txtTimeInterval.setBounds(268, 35, 114, 22);
            contentPane.add(txtTimeInterval);

            txtSaveDir = new JTextField();
            txtSaveDir.setColumns(10);
            txtSaveDir.setBounds(20, 92, 341, 22);
            contentPane.add(txtSaveDir);

            JButton btnBrowse = new JButton("Browse");
            btnBrowse.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    JFileChooser chooser = new JFileChooser();
                    chooser.setCurrentDirectory(new java.io.File("."));
                    chooser.setDialogTitle("Save Directory");
                    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    chooser.setAcceptAllFileFilterUsed(false);

                    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {

                      txtSaveDir.setText(chooser.getSelectedFile().toString());
                    } else {

                    }

                }
            });
            btnBrowse.setBounds(371, 92, 114, 23);
            contentPane.add(btnBrowse);

            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(20, 146, 1201, 220);
            contentPane.add(scrollPane);

            ResTable = new JTable();        
            ResTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

            JScrollPane scrollPane_1 = new JScrollPane();
            scrollPane_1.setBounds(21, 387, 1053, 330);
            contentPane.add(scrollPane_1);

            tblResult = new JTable();
            tblResult.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                     if (e.getClickCount() == 2){
                            int row=tblResult.rowAtPoint(e.getPoint());
                            LogInForm lg = new LogInForm();
                            lg.setHub(1);
                            lg.setRfidKey(tblResult.getValueAt(row, 1).toString());
                            lg.show();

                     }

                }
            });

            scrollPane_1.setViewportView(tblResult);
            setTable();
            String[][] whitelist = mysql.loadActiveKeys();

            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  

            for (int a = 0; a< whitelist.length;a++){
                try {
                    if (whitelist[a][8].length() <5) {
                        String Res = mysql.updateLastSeen(whitelist[a][1], getDateandTime());
                        addRow(whitelist[a][0],whitelist[a][1], getDateandTime(),
                                whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model);
                    }else {
                        Date d = format1.parse(whitelist[a][2]);
                        Date d1 = format1.parse(whitelist[a][8]);                               

                        long timeDiff = d1.getTime() - d.getTime();
                        if (timeDiff < 60000){
                            String Res = mysql.updateLastSeen(whitelist[a][1], getDateandTime());
                                    addRow(whitelist[a][0],whitelist[a][1], getDateandTime(),
                                            whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model);
                        }
                        else {
                            addRow(whitelist[a][0],whitelist[a][1],whitelist[a][2],
                                    whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model1);

                        }
                    }

                }catch(Exception e) {}
            }
            // testing the color
            setCellBackground(Color.WHITE,1);
            tblResult.setBackground(Color.red);

            //=======================================
            scrollPane.setViewportView(ResTable);

            btnAdminPanel = new JButton("Admin Panel");
            btnAdminPanel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    LogInForm login = new LogInForm();
                    login.show();
                    dispose();
                }
            });
            btnAdminPanel.setBounds(1084, 666, 137, 22);
            contentPane.add(btnAdminPanel);

            lblLost = new JLabel("Lost");
            lblLost.setFont(new Font("Tekton Pro Cond", Font.BOLD, 16));            
            lblLost.setBounds(1115, 633, 124, 22);
            contentPane.add(lblLost);

            textField_4 = new JTextField();
            textField_4.setBackground(Color.RED);
            textField_4.setColumns(10);
            textField_4.setBounds(1084, 638, 21, 11);
            contentPane.add(textField_4);

            btnConnect = new JButton("Connect");
            btnConnect.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    if ((txtSaveDir.getText().toString().equals("")) || (txtTimeInterval.getText().toString().equals(""))) {
                        showMessage("PLEASE FILL OUT FIELDS");
                    }
                    else {

                        rfid = new RfidTagSearch();
                        if (btnConnect.getText().toString().equals("Connect")) {

                            if (rfid.isConnected()) {
                                lbStatus.setText("Reconnected to Reader");
                                btnConnect.setText("Disconnect");
                                btnStart.setEnabled(true);
                                btnStop.setEnabled(false);
                                txtIP.setEnabled(false);
                                txtPort.setEnabled(false);
                                txtSaveDir.setEditable(false);
                                txtTimeInterval.setEditable(false);
                            }
                            else {
                                try {
                                    rfid.connectToReader("169.254.10.1",5084);
                                    lbStatus.setText(rfid.getStrResult());
                                } catch (Exception e) {
                                    // TODO Auto-generated catch block
                                    showMessage(e.toString());
                                }
                                String res = rfid.getResult();
                                if (res.equals("Success")) {
                                    btnConnect.setText("Disconnect");
                                    btnStart.setEnabled(true);
                                    btnStop.setEnabled(false);
                                    txtIP.setEnabled(false);
                                    txtPort.setEnabled(false);
                                    txtSaveDir.setEditable(false);
                                    txtTimeInterval.setEditable(false);
                                }
                                else {showMessage(rfid.getStrResult());}    
                            }

                        }
                        else {
                            try {
                                rfid.disconnectToReader();
                                lbStatus.setText("Disconnected to Reader");
                                btnConnect.setText("Connect");
                                btnStart.setEnabled(false);
                                btnStop.setEnabled(false);
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                showMessage(e.toString());
                                e.printStackTrace();
                            }
                        }

                    }

                }
            });
            btnConnect.setBounds(1099, 429, 122, 41);
            contentPane.add(btnConnect);


            btnStart = new JButton("Start");
            btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {

                        btnStop.setEnabled(true);
                        btnConnect.setEnabled(false);
                        btnStart.setEnabled(false);


                        rfid.setSaveDirectory(txtSaveDir.getText().toString());
                        rfid.startScanning();
                        rfid.setTimer(Integer.valueOf(txtTimeInterval.getText().toString()));
                        startTmer();
                        lbStatus.setText("Scan Started");
                        System.out.println(getDateandTime());
                    } catch (InterruptedException | InvalidUsageException | OperationFailureException e1) {
                        // TODO Auto-generated catch block
                        showMessage(e1.toString());
                        e1.printStackTrace();
                    }

                }
            });
            btnStart.setEnabled(false);
            btnStart.setBounds(1099, 487, 122, 41);
            contentPane.add(btnStart);

            btnStop = new JButton("Stop");
            btnStop.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        rfid.stopScanning();
                        lbStatus.setText("Scanning Stopped");
                        btnStop.setEnabled(false);
                        btnStart.setEnabled(true);
                        btnConnect.setEnabled(true);
                        timer.cancel();
                    } catch (InvalidUsageException | OperationFailureException | InterruptedException e1) {
                        // TODO Auto-generated catch block
                        showMessage(e1.toString());
                    }

                }
            });
            btnStop.setEnabled(false);
            btnStop.setBounds(1099, 550, 122, 41);
            contentPane.add(btnStop);

            label = new JLabel("Status : ");
            label.setForeground(new Color(204, 0, 0));
            label.setFont(new Font("Tekton Pro Cond", Font.BOLD, 20));
            label.setBounds(409, 38, 107, 22);
            contentPane.add(label);

            lbStatus = new JLabel("Not Connected");
            lbStatus.setFont(new Font("Tekton Pro Cond", Font.BOLD, 16));
            lbStatus.setBounds(526, 32, 212, 26);
            contentPane.add(lbStatus);


        }

        // Adding row to the table
        public void addRow(String stockNum, String rfidNum, String DateLastSeen, String DateLost, String year,String color, String Model, DefaultTableModel model){
            Object[] row = new Object[7];
            row[0] = stockNum;
            row[1] = rfidNum;
            row[2] = DateLastSeen.substring(5, DateLastSeen.length());
            row[3] = DateLost;
            row[4] = year;
            row[5] = color;
            row[6] = Model;

            model.insertRow(0,row);
        }


        // setting background of the table
        public void setCellBackground(Color color, int stat){
            ResTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
            {
                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                {
                    final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    if (stat == 0){
                        c.setForeground(color);

                    }
                    else{
                        c.setForeground(Color.black);                   
                    }
                    return c;
                }
            });

        }


        public void showMessage(String mess){
            JOptionPane.showMessageDialog(null, mess,"Error",JOptionPane.INFORMATION_MESSAGE);
        }

        ArrayList<String> key;
        ArrayList<String> lost = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        public void startTmer(){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                  @Override
                  public void run() {



                        key = rfid.getSeenKey();
                        if (key.size() > 0) {
                            for (int c=0;c<key.size();c++) {
                                String r = mysql.updateLastSeen(key.get(c), getDateandTime());
                            }
                        }
                        key.clear();


                        String[][] whitelist = mysql.loadActiveKeys();
                        if (whitelist.length > 0) {

                            ResTable.removeAll();
                            model.setRowCount(0);
                            tblResult.removeAll();
                            model1.setRowCount(0);

                            for (int a = 0; a< whitelist.length;a++){
                                try {

                                    Date d = format.parse(whitelist[a][2]);
                                    Date d1;
                                    if (whitelist[a][8].length() <5) {
                                        d1 = format.parse(getDateandTime());
                                    }
                                    else {
                                        d1 = format.parse(whitelist[a][8]);                             
                                    }
                                    long timeDiff = d1.getTime() - d.getTime();

                                    if (timeDiff < 60000){

                                        addRow(whitelist[a][0],whitelist[a][1],whitelist[a][2],
                                                whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model);
                                    }else {
                                        if (lost.size() <= 0) {
                                            lost.add(whitelist[a][1]);
                                            if (whitelist[a][8].length() <=5) {
                                                String res = mysql.updateLostDate(whitelist[a][1], getDateandTime());
                                                if (res.equals("Success"))
                                                addRow(whitelist[a][0],whitelist[a][1],whitelist[a][2],
                                                        whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model1);
                                                else {
                                                    System.out.println(res);
                                                }

                                            }else {
                                                addRow(whitelist[a][0],whitelist[a][1],whitelist[a][2],
                                                        whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model1);                                       
                                            }
                                        }else {
                                            for (int b = 0; b<lost.size();b++) {
                                                if (lost.get(b).equals(whitelist[a][1])) {
                                                }else {
                                                    if (whitelist[a][8].length() <=5) {
                                                        String res = mysql.updateLostDate(whitelist[a][1], getDateandTime());
                                                        //log.write(getDateandTime() +"," + whitelist[a][2] + System.getProperty( "line.separator"));
                                                        if (res.equals("Success"))
                                                        addRow(whitelist[a][0],whitelist[a][1],whitelist[a][2],
                                                                whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model1);
                                                        else {
                                                            System.out.println(res);
                                                        }

                                                    }else {
                                                        //log.write(whitelist[a][8] +"," + whitelist[a][2] + System.getProperty( "line.separator"));
                                                        addRow(whitelist[a][0],whitelist[a][1],whitelist[a][2],
                                                                whitelist[a][8],whitelist[a][5],whitelist[a][6],whitelist[a][7], model1);                                       
                                                    }

                                                }
                                            }
                                        }

                                    }

                                } catch (ParseException e) {
                                    // TODO Auto-generated catch block
                                    System.out.println("inside catch " + getDateandTime());
                                    System.out.print(e.toString());

                                    e.printStackTrace();
                                }

                            }

                        }

                        lost.clear();


                  }
                }, 1000, 1000); 

        }


        public String getDateandTime(){
            String res = "";
            LocalDateTime myDateObj = LocalDateTime.now();
            DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = myDateObj.format(myFormatObj);

            res = formattedDate.toString();
            return res;
        }
    }

Error Log

    Status Notification INVENTORY_START_EVENT
    2019-12-09 05:54:55
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
        at java.util.Vector.elementAt(Unknown Source)
        at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
        at javax.swing.JTable.getValueAt(Unknown Source)
        at javax.swing.JTable.prepareRenderer(Unknown Source)
        at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
        at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
        at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
        at javax.swing.plaf.ComponentUI.update(Unknown Source)
        at javax.swing.JComponent.paintComponent(Unknown Source)
        at javax.swing.JComponent.paint(Unknown Source)
        at javax.swing.JComponent.paintToOffscreen(Unknown Source)
        at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
        at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
        at javax.swing.RepaintManager.paint(Unknown Source)
        at javax.swing.JComponent._paintImmediately(Unknown Source)
        at javax.swing.JComponent.paintImmediately(Unknown Source)
        at javax.swing.RepaintManager$4.run(Unknown Source)
        at javax.swing.RepaintManager$4.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
        at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
        at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
        at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
        at javax.swing.RepaintManager.access$1200(Unknown Source)
        at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
        at java.awt.event.InvocationEvent.dispatch(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$500(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)
trincot
  • 317,000
  • 35
  • 244
  • 286
  • It's not possible to help without seeing the code Please post an [mre] that demonstrates the problem. And keep it `minimal` – WJS Dec 08 '19 at 15:23
  • Note: The garbage collector already deletes collected garbage from the JVM. If you get a heap space OutOfMemoryError, it means that there is nothing that the garbage collector can collect. That is, that all of the heap space is taken by objects that are reachable. – RealSkeptic Dec 08 '19 at 15:26
  • OOME is thrown few types of errors e.g. heap space exhaustion or file descriptor limit reached. First understand which OOME flavour you have encountered and then look for fix. – Karol Dowbecki Dec 08 '19 at 15:29
  • I have updated the post and insert the image and the code used by the reader and Jtble. garbage colector runs in the Rfid Reader – Animoto Dito Dec 09 '19 at 10:46
  • @AnimotoDito Call to gc does not force GC, it has no immediate effect. OOME could caused by memory leak. Unless you post the full code and log trace, it's impossible to find the cause of the leak in your program. – Mạnh Quyết Nguyễn Dec 09 '19 at 11:17
  • updated . this is the error I am getting before heap space. after 10 minutes the application gives me heap space memory shortage – Animoto Dito Dec 09 '19 at 11:51
  • Start JVM with [automatic dump](https://stackoverflow.com/questions/34076680/java-out-of-memory-automatic-heap-dump-file-name) on OOME or [create one](https://stackoverflow.com/questions/407612/how-to-get-a-thread-and-heap-dump-of-a-java-process-on-windows-thats-not-runnin) after program runs for a while and then [look](https://dzone.com/articles/java-heap-dump-analyzer-1) what objects consume memory. Then check where those objects are created in your program and why the are retained in memory. – Roman-Stop RU aggression in UA Dec 09 '19 at 14:46
  • @AnimotoDito could you add the code of mysql class? – Mạnh Quyết Nguyễn Dec 10 '19 at 06:44

1 Answers1

-1

Out of Memory(OOM) error occurs if the application has exceeded the amount of memory allocated by the JVM.

You can start the JVM with more memory allocation. The JVM command -Xmx<size> to specify the maximum heap size.

java -Xmx1024m -jar your-application.jar

If your FileWriter is not buffered it can make the writing process very slow. Therefore you should wrap your FileWriter in a BufferedWriter stream.

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("text.txt", true)));
    out.println("the text you want to append");
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (out != null) {
        out.close();
    }
} 

One of the most expensive operations on a computer system is IO, instead of writing to the file continuously you should store the tags in StringBuffer when it reaches a certain size you write it to the file.

Thecarisma
  • 1,424
  • 18
  • 19