Java:懒惰加载Singleton和反射攻击? [英] Java: Lazy loading Singleton and reflection attack?

查看:155
本文介绍了Java:懒惰加载Singleton和反射攻击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我通过holder idiom或double checked lock实现Singleton,而不是调用'getInstance()',使用反射来实例化它,然后在其上调用'getInstance()',这将创建两个实例,打破模式。

If I implement a Singleton either through holder idiom or double checked locking, but instead of calling 'getInstance()', use reflection to instantiate it, and then call 'getInstance()' on it, this would create two instances, breaking the pattern.

所以我在类中添加一个静态'counter'成员,在类的私有构造函数中递增它,如果它超过'1'则抛出异常。但是在这种情况下,如果我首先通过反射进行实例化,那么没有其他人能够在不抛出异常的情况下调用'getInstance()'。

So I add a static 'counter' member to the class, increment it in the class's private constructor, and throw an exception if it crosses '1'. But in that case, if I first instantiate through reflection, nobody else would be able to call 'getInstance()' without throwing an Exception.

那么我如何延迟加载单身人士还能防止这次袭击? (我知道'Enum'模式,但有些人觉得它实际上是一个黑客。请检查对此接受的答案的评论:这个单身人士对序列化和反射攻击都有抵抗吗?和顺便说一下,我的问题是不同的。)

So how do I lazy load a Singleton yet prevent it from this attack? (I'm aware of 'Enum' pattern, but some feel that it's actually a hack. Check comments on the accepted answer of this: is this Singleton resistant to both Serialization and Reflection Attacks? and btw, my question is different).

编辑:我认为通过使用静态计数器字段,基于类的同步构造函数并将this赋给静态成员,可以在DCL的情况下阻止它。但是,不确定如何在持有人习语的情况下防止它。

I think it's possible to prevent it in case of DCL, by using the static counter field, class-based synchronized constructor and assigning 'this' to the static member. However, not sure how to prevent it in case of holder idiom.

推荐答案

我个人坚持使用枚举,但也有初始化按需持有人(IODH)成语

Personally I stick with Enums, but there is also the Initialization on Demand Holder (IODH) idiom

static class SingletonHolder {
  static Singleton instance = new Singleton();    
}

public static Singleton getInstance() {
  return SingletonHolder.instance;
}

这出现在Effective Java(第48项)中,但我第一次听说过它来自疯狂鲍勃的帖子

This appears in Effective Java (item 48), but I first heard of it from a post by crazy bob

http://blog.crazybob.org/2007/01/lazy-loading-singletons.html

参见 http://www.cs.umd.edu/~pugh/ java / memoryModel / jsr-133-faq.html#dcl 进行了大量有趣的讨论。

See http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl for lots of interesting discussion.

这篇关于Java:懒惰加载Singleton和反射攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆