Java Singleton Pattern Thread Safe

preview_player
Показать описание
Enjoy! :-)
Thank you for commenting and asking questions.

Checkout or buy the Introduction to Algorithms book at Amazon:

The code is located here:
Follow me on twitter:
Support me on Patreon:

As an Amazon Associate I earn from qualifying purchases.
Check out the stuff that I like (always updated):
Рекомендации по теме
Комментарии
Автор

You need to make your instance variable volatile, otherwise one cpu thread can have one view of the enum singleton instance and another cpu thread can have another view. They can have different values due to local CPU caches which has not been propagated to main cache / main memory. That is, memory address X will contain the value null in one CPU, and memory address X will point to an object in another CPU. The volatile keyword forces all cpu threads to see the same value.

Foobarski
Автор

Thank you for "shaming" the singleton pattern. The singleton pattern has its places, but if you are using it all over the place, you are simple not programming in an object oriented manner.

Foobarski