多线程环境中的 Java WS Authenticator

发布于 2024-09-26 20:01:35 字数 645 浏览 1 评论 0 原文

目前,我正在努力解决 Sun 类 java.net.Authenticator 中的错误。看来Authenticator类有一个系统范围的静态Authenticator。这会导致我的多线程应用程序出现以下问题。

  1. 线程 1 - 对用户 1 进行身份验证
  2. 线程 2 - 对用户 2 进行身份验证
  3. 线程 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.

  1. Thread 1 - Authenticates for User 1
  2. Thread 2 - Authenticates for User 2
  3. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱,才寂寞 2024-10-03 20:01:35

根据我的经验,最好的选择是放弃内置的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文