目前,我正在努力解决 Sun 类 java.net.Authenticator
中的错误。看来Authenticator
类有一个系统范围的静态Authenticator
。这会导致我的多线程应用程序出现以下问题。
- 线程 1 - 对用户 1 进行身份验证
- 线程 2 - 对用户 2 进行身份验证
- 线程 1 - 执行代码以下载用户 1 的消息
此时,系统将获取用户 2 的消息而不是用户 1 的消息。
我已经尝试过寻找解决方案。许多人建议尝试以下代码:
AuthCacheValue.setAuthCache(new AuthCacheImpl());
Authenticator.setDefault(exchangeAuthenticator);
但是,这对我不起作用,因为我的应用程序是多线程的(exchangeAuthenticator
将始终设置为在最新线程中初始化的身份验证器)。
如果有人有任何想法,即使现在黑客也可以,我真的很感激,因为目前唯一的“简洁”解决方案是在主执行方法上放置一个 synchronized
,并使用对性能产生巨大影响。
At the moment I am struggling with a bug in Sun's class java.net.Authenticator
. It seems that the Authenticator
class has a system wide static Authenticator
. This results in the following problem in my multi-threaded application.
- Thread 1 - Authenticates for User 1
- Thread 2 - Authenticates for User 2
- Thread 1 - Executes the code to download messages for User 1
At this point, the system will get the messages for User 2 instead of the messages for User 1.
I have tried searching for a solution. Many suggested trying the following code:
AuthCacheValue.setAuthCache(new AuthCacheImpl());
Authenticator.setDefault(exchangeAuthenticator);
However, this does not work for me since my application is multi-threaded (exchangeAuthenticator
will always be set to the authenticator initialized in the latest thread).
If anyone has any idea, even a hack would do at the moment, I would really appreciate that, since at the moment the only 'neat' solution is to place a synchronized
on the main execution method with a dramatic effect on performance.
发布评论
评论(1)
根据我的经验,最好的选择是放弃内置的 http 支持并获取 Apache 的 HttpClient 。
如果这不是一个选项,请创建一个扩展 Authenticator 的单个对象,但将用户名和密码存储在 ThreadLocal 实例。这样每个线程都可以检索它自己的值。
In my experience, your best bet is to ditch the builtin http support and get Apache's HttpClient.
If that's not an option, create a single object extending Authenticator, but store the username and password in ThreadLocal instances. That way each thread can retrieve it's own values.