做过JAVA编程的都知道,在JAVA中有一种垃圾收集器的机制,当它运行时(通常在系统内存低到一定限度时自动运行),会回收不再使用的对象所占用的内存,所以,在JAVA程序中,我们通常只考虑创建对象,而" name="description" />
下一页 1 2 3
Java中finalize()的另类用法(图一)" />
package com; public class user { public String name=""; public String sessionId=""; } |
package com; import java.util.Vector; import com.user; public class testSession { public user User; private Vector vsid; public testSession() { User=new user(); } public boolean verify(String username,String password) throws Exception //验证用户/密码 { return true; } public void setSessionVar(String sesid,Vector sid) { this.User.sessionId=sesid; this.vsid=sid; } private static synchronized void addappses(user puser, Vector pvsid) { //记录一个新连接的用户 int pos=-1; user l_user; if (puser==null || pvsid==null) return; for(int i=0;i<pvsid.size();i++){ l_user=(user)pvsid.get(i); if(l_user.sessionId.equals(puser.sessionId)){ pos=i; break; } } if(pos==-1){ pvsid.add(puser); } else{ pvsid.set(pos,puser); } } private static synchronized void removeappses(user puser, Vector pvsid) { //移除一个退出的用户 int pos=-1; user l_user; if (puser==null || pvsid==null) return; for(int i=0;i<pvsid.size();i++){ l_user=(user)pvsid.get(i); if(l_user.sessionId.equals(puser.sessionId)){ pos=i; break; } } if(pos!=-1){ pvsid.remove(pos); } } protected void finalize() { this.removeappses(this.User,this.vsid); } public boolean login(String username) throws Exception { //处理登录 this.User.name=username; this.addappses(this.User,this.vsid); return true; } public boolean logout() throws Exception { //处理注销 this. finalize(); this.User=null; this.vsid=null; return true; } } |