[英]@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.