2

Effective Java 2nd describes the Enum Implementation as the best practice to implement a Singleton in Java.

But the advantage of that implementation against the Static Holder Implementation is that the enum can prevent the reflection attack.

So, there comes the question: Why do we need to prevent the reflection attack of singleton?

The other implementations of Java Singleton are just resolving the issues of multiple threads and lazy initialization.

These problems will and often appear at the daily development, but the reflection attack seems more like a Security Issue.

If the attacker can hack and crack your program, he and she could do whatever he and she wants, it seems it is no need to break the Singleton.

Wafer Li
  • 43
  • 7
  • 1
    Reflection isn't always used for an "attack." The enum singleton is used to guard against legitimate uses of reflection breaking your code. – 4castle May 25 '17 at 01:54
  • @4castle Could you post a example of it? I still don't understand how to "legitimate uses of reflection breaking the singleton". If you want to not affected by serialization, just don't implement that interface. Use the reflection with a singleton seems really rare. – Wafer Li May 25 '17 at 02:04
  • Possible duplicate of [What is reflection and why is it useful?](https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful) – 4castle May 25 '17 at 02:10
  • Honestly, this line of thinking is an absolute overkill. Almost anything can be achieved with reflection (until Java 9, at least) and I've never seen a library (JVM's own libs included) that protects against reflective manipulation, because that's the job of `SecurityManager`. If someone wants to defeat the singleton by reflection - you should probably let them. – kaqqao Jun 01 '17 at 22:28

1 Answers1

3

@Wafer Li, in theory reflection could create a second instance of a non-enum singleton, and so could deserialization. These are not "attacks" but ways that client code could defeat singletonness. The whole point of API writing is to guarantee documented behavior. If one leaves such a huge hole in the guarantee, why bother writing a singleton at all?

Also, lazy initialization of singletons is useless. Pointless. Static holder is redundant and just a whole bunch of code.

So why resist simple, elegant, fully-implemented, standard, best-practice enum for singletons?

Why?

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
  • I am not resist the `enum` for singleton. I do think the `enum` is more elegant than the static holder. I am just curious about why border the "reflection attack". It now turns out to prevent the problem of deserialization. Thanks. – Wafer Li May 25 '17 at 06:15