找了一下,百度第一条说了等于没说。现在给出分析以及解决方案:
Authenticator类对象每次都是创建新的对象。然后再看
先的问题就变成了怎么改,就这么改:
Session session = Session.getDefaultInstance(props,
CtsAuthenticator.getCtsAuthenticator(data.get(USER_NAME), data.get(PASSWORD))
);
static class CtsAuthenticator extends Authenticator{
private static Map<String,CtsAuthenticator> ctsAuthenticatorMap=new HashMap<>(10);
public final static CtsAuthenticator getCtsAuthenticator(String userName, String password){
String key = "userName:"+userName+" password:"+password;
CtsAuthenticator ctsAuthenticator = ctsAuthenticatorMap.get(key);
if(ctsAuthenticator!=null){
return ctsAuthenticator;
}
return newInstance(userName, password, key);
}
private synchronized static CtsAuthenticator newInstance(String userName, String password, String key) {
CtsAuthenticator newInstance = new CtsAuthenticator(userName,password);
ctsAuthenticatorMap.put(key,newInstance);
return newInstance;
}
private String userName;
private String password;
private CtsAuthenticator(String userName,String password){
this.userName=userName;
this.password=password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
就是把 Authenticator 缓存起来。