如何使单例范围对象线程安全 (Guice + Owasp ESAPI)
我目前正在使用 Owasp ESAPI 来管理我的 java Web 应用程序中的身份验证,并且我正在使用 guice.injectMembers(this) 注入 Singleton MyAuthenticator。我想放弃这种方法并使用 guice 创建的 Singleton-Scoped 对象。我喜欢 ESAPI 单例的线程安全性,以及一般单例的安全性,使用双重检查锁定、IODH 习惯用法或 Bloch 的 Enum INSTANCE 风格。
我需要对我的 Guicified Singleton-Scoped Authenticator 做什么才能使其线程安全,以及我用来获取和设置当前用户的 ThreadLocal 字段?
我想让整个应用程序通过依赖注入工作,但不希望它在 Web 应用程序并发访问时中断。有什么建议或常见陷阱吗?
我正在使用的 ThreadLocal 对象如下代码所示:
private final ThreadLocalUser currentUser = new ThreadLocalUser();
private class ThreadLocalUser extends InheritableThreadLocal<User> {
@Override
public User initialValue() {
return User.ANONYMOUS;
}
public User getUser() {
return super.get();
}
public void setUser(User newUser) {
super.set(newUser);
}
}
I am currently using the Owasp ESAPI to manage authentication in my java web application, and I am injecting the Singleton MyAuthenticator with guice.injectMembers(this). I would like to step away from this approach and use a guice-created Singleton-Scoped object. I liked the thread-safety of the ESAPI singleton, and the safety of singletons in general, using Double-Checked Locking, IODH Idiom, or Bloch's Enum INSTANCE style.
What do I need to do to my Guicified Singleton-Scoped Authenticator to make it thread-safe, as well as the ThreadLocal field I am using to get and set my current User?
I would like to make the entire application work with dependency-injection, but don't want it to break upon web-app concurrent access. Any suggestions or common pitfalls?
The ThreadLocal object I am using looks like the code below:
private final ThreadLocalUser currentUser = new ThreadLocalUser();
private class ThreadLocalUser extends InheritableThreadLocal<User> {
@Override
public User initialValue() {
return User.ANONYMOUS;
}
public User getUser() {
return super.get();
}
public void setUser(User newUser) {
super.set(newUser);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,我对 Owasp ESAPI 的了解不够,无法给出具体的答案,但您可能会幸运地研究一下 Guice 的 AOP 支持。您可以拦截类上的所有方法调用并提供您喜欢的任何并发行为。
http://code.google.com/p/google-guice/wiki/AOP
Unfortunately I don't know enough about Owasp ESAPI to give a specific answer, but you may have some luck looking into Guice's AOP support. You can intercept all method invocations on the class and provide whatever concurrency behavior you like.
http://code.google.com/p/google-guice/wiki/AOP
请注意在 Java 中使用“双重检查锁定”模式。这种设计模式在 Java 中不能可靠地工作(例如,请参阅 http ://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)除非您将单例实例声明为“易失性” 。
Beware using the "Double-Check Locking" pattern in Java. This design pattern doesn't reliably work in Java (for instance, see http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html) unless you declare the singleton instance as "volatile".