[英]@singleton behaving like @stateless bean
我正在研究一个应用程序(在java中的enterprize应用程序),其中我需要的是单个实例,由多个线程同时共享,我已经使用了@singleton。 当每个用户登录一个值时,通过调用setTeleCallersDetails()远程方法在telecallers List中设置。 但是当某个用户登录的数量超过15时,@ someton开始表现得像@stateless bean,因为setTeleCallersDetails()开始在新的tellcaller arraylist中添加值。 任何人都可以告诉实际如何解决这个问题我的代码
@Singleton
@Startup
public class UserSessionBean implements UserRemote {
volatile List<UserDetails> user;
volatile List<UserDetails> telecallers;
volatile List notloggedlt;
/**
* Default constructor.
* @return
*/
@PostConstruct
private void startup() {
// TODO Auto-generated constructor stub
if(user == null){
user = new ArrayList<UserDetails>();
}
if(telecallers == null){
telecallers = new ArrayList<UserDetails>();
}
if(notloggedlt == null){
notloggedlt = new ArrayList();
}
}
public List<UserDetails> getUserDetails(){
return user;
}
public List<UserDetails> getTeleCallersDetails(){
return telecallers;
}
public List getNotKLoggedInUsersDetails(){
return notloggedlt;
}
@Lock(LockType.WRITE)
public void setUserDetails(UserDetails objUser){
if(!user.isEmpty()){
Collections.sort(user);
int location = Collections.binarySearch(user, new UserDetails(objUser.getUserId()));
if (location >= 0) {
user.remove(location);
}
}
user.add(objUser);
}
@Lock(LockType.WRITE)
public void removeUserDetails(String userId){
Collections.sort(user);
int location = Collections.binarySearch(user, new UserDetails(userId));
if (location >= 0) {
user.remove(location);
}
}
@Lock(LockType.WRITE)
public void removeTeleCallersDetails(String userId){
Collections.sort(telecallers);
int location = Collections.binarySearch(telecallers, new UserDetails(userId));
if (location >= 0) {
telecallers.remove(location);
}
}
@Lock(LockType.WRITE)
public void setNotKLoggedInUsersDetails(List notloggedusers){
this.notloggedlt = notloggedusers;
}
@Lock(LockType.WRITE)
public void setNotKLoggedInUserDetail(UserDetails objUser){
notloggedlt.add(objUser);
}
@Lock(LockType.WRITE)
public void setTeleCallersDetails(UserDetails objUser){
if(!telecallers.isEmpty()){
Collections.sort(telecallers);
int location = Collections.binarySearch(telecallers, new UserDetails(objUser.getUserId()));
if (location >= 0) {
telecallers.remove(location);
}
}
telecallers.add(objUser);
}
}
垃圾收集:如果单个类被垃圾收集,那么在需要时再次通过创建新实例重新加载。 当没有对此类及其实例的引用时,就会发生这种情况; 所有字段都默认/重新初始化,之前的状态丢失。
类加载器:如果有多个类加载器,则可以存在多个副本,每个副本都可以拥有自己的单例实例。
可能在你的情况下,线程没有持有对单例类的任何引用,因为一旦它们完成,引用就会被销毁并且单例可能会被垃圾收集 。
由于单例bean默认使用WRITE
锁定容器管理并发的方法,因此您不需要为字段显示指定LockType
,为字段显示volatile
,因为一次只能访问一个客户端。
您可以尝试将记录器添加到默认构造函数,启动和销毁方法以获取想法,下面真正发生的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.