Java Reference
In-Depth Information
It has been briel y mentioned that the singleton pattern has fallen out of favor to the point in
which many developers and architects now consider it an anti‐pattern. The singleton pattern's
unpopularity extends from problems caused by its overuse and abuse and its evident shortcomings
in multithreaded applications.
Programmers have overused and abused the singleton pattern because it is a simple pattern to
implement. So every class becomes a singleton. This has presented a nightmare for developers who
must maintain the code, and it has become an even greater challenge for those who have to refactor
the singletons into object‐orientated code when it is discovered that more than one instance of a
singleton class is required.
The use of singleton classes has made testability more complicated because global states need to be
instantiated to run a simple unit test. Furthermore, singletons have made tests less deterministic
because these states might change, affecting the outcome of the tests.
You have seen in the code examples the numerous difi culties that singletons pose in multithread
environments. It was difi cult to create a singleton that was guaranteed thread safe before Java SE 5
and the introduction of the enum type.
However, with the advances made in Java EE, the problem of thread‐safe singletons has largely been
resolved with the @Singleton annotation and container control concurrency.
The container controls the creation of the singleton and ensures that no business method is called
before the @PostContrust completes. The container also controls the concurrency of access to
the bean via the @ConcurrencyManagement annotation, and its associated @LockType annotation
allows i ne‐grain access control over each method.
By no means has every problem of the singleton been resolved. There could still be problems
in multinode environments if the bean is used to access back‐end non‐thread‐safe resources.
Bottlenecks and tight coupling of classes could be additional problems.
Even though the singleton pattern has suffered from abuse and overuse by developers,
leading to its eventual relegation to an anti‐pattern, it has nevertheless matured
substantially since it was introduced by GoF and should be reconsidered as a valuable and viable
design pattern.
1. Design a web page hit counter with two methods: one method that increments the count, and
one method that gets the latest count. Ensure that it is thread safe by dei ning the appropri-
ate lock types.
2. Design a simple cache that stores a list of topics for a library management application. The
data should be loaded into the cache on application startup. Add methods to retrieve topics
based on different criteria, such as ISBN, author, and genre.
Search WWH ::

Custom Search