Singleton in Java

Topics interesting only for Java programmers

Link to this posting

Postby Ursego » 05 Mar 2019, 07:55

To see the keywords colored, save the following text in a text file and open it in a Java compiler (or in Notepad++ and select in the menu: Language > J > Java).

Code: Select all
// The singleton pattern is a creational pattern focused on creating only one instance of an object in memory within an application, sharable by all classes and threads within the application. The globally available object created by the singleton pattern is referred to as a singleton. Singletons may also improve performance by loading reusable data that would otherwise be time consuming to store and reload each time it is needed. Singleton has:
//   * a private constructor;
//   * a static factory method, usually named getInstance; must be synchronized, which means only one thread will be allowed in the method at a time, ensuring that only one object is created.
public class VisitorTicketTracker {
   private static VisitorTicketTracker instance;
   private VisitorTicketTracker() {} // private constructor!
   public static synchronized VisitorTicketTracker getInstance() { // synchronized!
      if (instance == null) {
         instance = new VisitorTicketTracker();
      return instance;
   // ...other members...
// If the instance is created in a static initializer, then the factory method doesn't need to be synchronized:
public class StaffRegister {
   private static final StaffRegister instance;
   static {
      instance = new StaffRegister();
   private StaffRegister() {}
   public static StaffRegister getInstance() { return instance; }
   // ...other members...
User avatar
Site Admin
Posts: 143
Joined: 19 Feb 2013, 20:33

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

Traffic Counter

free counters

eXTReMe Tracker