Java中的电子邮件服务引发“内存不足”错误

我正在后台(在命令提示符下)运行电子邮件服务,这是为了继续运行并在队列表中提取记录以进行处理.

 

这是我的Email.java

 

public class Email {


    MySqlConnect con=new MySqlConnect();
    public PreparedStatement preparedStatement = null;

    public Connection con1 = con.connect();

    public Email() throws Exception {


    }

    //pick up queue and send email
    public void email() throws Exception {


        try{

            while(true) {
                String sql = "SELECT id,subject,recipient,content FROM emailqueue WHERE status='Pending' ";
                PreparedStatement statement = con1.prepareStatement(sql);
                ResultSet rs = statement.executeQuery();

                while (rs.next()) {

                    String subject = rs.getString("subject");

                    String recipient = rs.getString("recipient");

                    String content = rs.getString("content");

                    String id = rs.getString("id");

                    sendEmail(recipient, subject, content, id);


                }

            }


        }catch(Exception e){

            e.printStackTrace();

        }
        con1.close();
        Thread.sleep(2000);

    }


//Schedule a service for picking email
    public void schedule(){

        Thread service;
        service = new Thread(new Runnable() {

            public void run() {
                try {

                    System.out.println("Email service is ready");
                    email();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        service.start();


    }



    public void sendEmail(String recipient, String subject, String content,String id) {
        try {

            //final String fromEmail = "lordjesus0371@gmail.com"; //requires valid gmail id
            // final String password = "htasia123"; // correct password for gmail id
          //  InitialContext ctx = new InitialContext();


            String host = get_attributevalue("MAIL_SERVER");
            String port = get_attributevalue("MAIL_PORT");
            final String senderaddress = get_attributevalue("SENDER_ADDRESS");
            final String password = get_attributevalue("MAIL_PASSWORD");



            System.out.println("Please Wait, sending email...");




            /*Setup mail server */

            Properties props = new Properties();

            props.put("mail.smtp.host", host); //SMTP Host
            props.put("mail.smtp.port", port); //TLS Port
            props.put("mail.smtp.auth", "true"); //enable authentication
            props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS





            //create Authenticator object to pass in Session.getInstance argument
            Authenticator auth = new Authenticator() {
                //override the getPasswordAuthentication method
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(senderaddress, password);
                }
            };
            Session session = Session.getInstance(props, auth);


            session.setDebug(true);


            // Define message
            MimeMessage message = new MimeMessage(session);
            // Set From: header field of the header.
            message.setFrom(new InternetAddress(senderaddress));
            message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
            // Set Subject: header field
            message.setSubject(subject);

            // Now set the actual message
            message.setText(content);


            Transport.send(message);

            delivered(id);
            System.out.print("Email sent");



        } catch (Exception e) {
            System.out.println(e.getMessage());
            try{
                error(id);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

        }


    }

在我的Main方法中:

 

public static void main(String[] args) throws Exception {



        Email runEmailService=new Email();

        runEmailService.schedule();



    }

它能够提取记录并处理电子邮件,但是一段时间后会抛出:

 

Exception in thread "Thread-1" java.lang.OutOfMemoryError: Java heap space

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Thread-1"

并且程序停止运行.

有没有一种方法可以防止这种情况的发生,使我的程序继续运行?

最佳答案

语句和结果集资源可能还没有被释放,并且因为您没有关闭它们而被保存在内存中.

 

考虑在while(rs.next())循环之后关闭它们:

 

rs.close(); 
statement.close();

请注意,您可以使用“尝试使用reousrces”来让事物自行关闭:

 

try (PreparedStatement statement = con1.prepareStatement(sql); ResultSet rs = statement.executeQuery())

cf. Java 7 Automatic Resource Management JDBC (try-with-resources statement)

 

public void email() throws Exception {

    String sql = "SELECT id,subject,recipient,content FROM emailqueue WHERE status='Pending' ";

    while (true) {

        try (PreparedStatement statement = con1.prepareStatement(sql); ResultSet rs = statement.executeQuery()) {

            while (rs.next()) {

                String subject = rs.getString("subject");

                String recipient = rs.getString("recipient");

                String content = rs.getString("content");

                String id = rs.getString("id");

                sendEmail(recipient, subject, content, id);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    con1.close();
    Thread.sleep(2000);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值