台灣最大程式設計社群網站
線上人數
1101
 
會員總數:246315
討論主題:189843
歡迎您免費加入會員
討論區列表 >> Java >> 請問這樣的程式有物件未釋放的問題嗎
[]  
[我要回覆]
回應主題 加入我的關注話題 檢舉此篇討論 將提問者加入個人黑名單
請問這樣的程式有物件未釋放的問題嗎
價值 : 30 QP  點閱數:1171 回應數:1
樓主

Albert
門外漢
0 4
36 1
發送站內信

大家好
小弟最近接手一個java的應用系統
運作時常常耗用到1g以上的記憶體
導致出現out of memory的錯誤

目前懷疑是下面會不斷被呼叫的程式碼所造成的
不知是否有那裡明確沒寫好(我不敢隨便改寫...)
導致記憶體都沒被釋放

這段程式主要功能是接受client post過來的資料
然後寫入DB及文字檔
謝謝

package gov.tcg.msg.web;


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.URI;
import java.util.*;
import java.util.logging.*;
import java.text.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import com.ares.util.hibernate.HibernateSessionFactory;
import gov.tcg.msg.bso.*;
import gov.tcg.msg.entity.*;
import org.hibernate.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

public class SyncExchangeServlet extends HttpServlet {
private static Logger logger=Logger.getLogger(SyncExchangeServlet.class.getName());
private static ResourceBundle rb0=ResourceBundle.getBundle("gov.tcg.msg.ResourcesString");
private static ResourceBundle rb=ResourceBundle.getBundle("gov.tcg.msg.exchange");

static final String CONTENT_TYPE="text/xml";

boolean filterRemoteIP=true;

private String backupDir=null;
public SyncExchangeServlet() {
try {
filterRemoteIP=Boolean.valueOf(rb.getString("exchange.synchronize.hostIPFilter")).booleanValue();
} catch (Exception ex) {
}
logger.info("Filter remote host ip:"+filterRemoteIP);
backupDir=rb.getString("exchange.backupdirroot");
}
public static void main(String[] args) {
SyncExchangeServlet syncExchangeServlet1 = new SyncExchangeServlet();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long s=System.currentTimeMillis();
response.setContentType(CONTENT_TYPE);
// PrintWriter out = response.getWriter();


String appid=request.getPathInfo().substring(1);

logger.info("request from "+request.getRemoteAddr());
logger.info("request uri:"+request.getRequestURI());

Application app=null;
Session sess=HibernateSessionFactory.getInstance().getSession();
int returnStatus=0;
String returnDesc="";
Transaction tran=null;
ExchangeLog excLog=new ExchangeLog();
try {
app=(Application)sess.get(Application.class,appid);


excLog.setExchangeDate(new Date());
excLog.setExchangeType("sy");
excLog.setFrom(app);

tran=sess.beginTransaction();
if (app==null){
logger.info("application '"+appid+"' is not found.");
excLog.setDescription(app==null?"Unknown application from.":"");
sess.save(excLog);
tran.commit();
returnStatus=2;
returnDesc="Application is not found.";
} else if (!app.isEnabled()) {
excLog.setDescription("Service for application "+app.getId()+" is not enabled");
} else {
String remoteHost=request.getRemoteAddr();
if (filterRemoteIP) {
if (app.getIp()!=null && app.getIp().length()>0 && !app.getIp().equals(remoteHost)) {
excLog.setDescription(MessageFormat.format(rb0.getString("exchange.sync.remoteHostNotAllow"),new Object[]{remoteHost}));
sess.save(excLog);
logger.info("Remote host from '"+remoteHost+"' is not allow");
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}

sess.save(excLog);
tran.commit();


File backupDir2=new File(backupDir,app.getId());
if (!backupDir2.exists())
backupDir2.mkdirs();
File logXmlFile=new File(backupDir2,excLog.getId()+"_"+String.valueOf((int)(Math.random()*1000000))+".xml");
this.writeToFile(request.getInputStream(),logXmlFile);
Message2DB msg2db=new Message2DB();
int count=msg2db.x2d(app,excLog,new FileInputStream(logXmlFile));
excLog.setDescription(
MessageFormat.format(
rb0.getString("exchange.sync.logDescription")
,new Object[]{String.valueOf(msg2db.getNewMessageCount())
,String.valueOf(msg2db.getUpdateMessageCount())
,String.valueOf(msg2db.getDeleteMessageCount())
,String.valueOf(msg2db.getDuplicateMessageCount())
,String.valueOf(msg2db.getErrorMessageCount())}));
tran=sess.beginTransaction();
sess.save(excLog);
tran.commit();
returnDesc=excLog.getDescription();
}
String desc=null;
xmlRespose(response.getOutputStream(),returnStatus,returnDesc);
}catch (Message2DBException ex) {
logger.log(Level.SEVERE,ex.getMessage(),ex);
String desc=ex.getMessage();
returnStatus=1;
try {
xmlRespose(response.getOutputStream(),returnStatus,desc);
tran=sess.beginTransaction();
excLog.setDescription(MessageFormat.format(rb0.getString("exchange.sync.exception"),new Object[]{ex.getClass().getName()}));
sess.save(excLog);
tran.commit();
} catch (Exception ex1) {
logger.log(Level.WARNING,"response client error.",ex1);
}
} finally {
if (sess!=null && sess.isOpen())
sess.close();
}
}

private void xmlRespose(OutputStream out,int status,String description) throws IOException {
Document doc=new Document();
Element root=new Element("message-exchange-protocol");
doc.addContent(root);

root.addContent(new Element("operation").addContent("syncMessagePost"))
.addContent(new Element("status").addContent(String.valueOf(status)));

if (description!=null)
root.addContent(new Element("description").addContent(description));
new XMLOutputter().output(doc,out);
}

private void writeToFile(InputStream in,File outFile) throws IOException {
FileOutputStream fos=null;
try {
fos=new FileOutputStream(outFile);
BufferedInputStream bis=new BufferedInputStream(in);
byte[] buf=new byte[1024];
int len=0;
while ((len=bis.read(buf))!=-1)
fos.write(buf,0,len);
}
finally {
if (fos!=null)
fos.close();
}

}
}

本篇文章發表於2012-03-06 17:21
目前尚無任何回覆
   

回覆
如要回應,請先登入.