mardi 21 avril 2020

Can you implement the Singleton pattern in Java 8+ using Optional

So, the typical Singleton pattern goes like this:

public class SampleObject {
  private static SampleObject sampleObject = null;

  private SampleObject() {}

  public static SampleObject getInstance() {
    if (sampleObject == null) sampleObject = new SampleObject();
    return sampleObject;
  }
}

I tried writing the getInstance() function using an Optional like so:

public static SampleObject getInstance() {
    sampleObject = Optional.ofNullable(sampleObject).orElse(new SampleObject());
    return sampleObject;
  }

For some strange reason it works for some classes and for some it just doesn't.

Am I implementing it wrong or is it just not possible to implement Singleton pattern using Optional?

****Edit*** When I run this bit of code

import java.util.*;

class ObjTracker {
  private static ObjTracker objTracker;

  private ObjTracker() {}

  public static ObjTracker getInstance() {
    objTracker = Optional.ofNullable(objTracker).orElse(new ObjTracker());
    return objTracker;
  }
}

class Main {

  public static void main(String[] args) {
    var objTracker = ObjTracker.getInstance();
    var objTracker1 = ObjTracker.getInstance();
    System.out.println(objTracker);
    System.out.println(objTracker1);
  }
}

objTracker and objTracker1 both equal to the same instance of ObjTracker, so the orElse does not always get executed.

Aucun commentaire:

Enregistrer un commentaire