Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum to implement multitons in Java

Tags:

java

enums

I would like to have a limited fixed catalogue of instances of a certain complex interface. The standard multiton pattern has some nice features such as lazy instantiation. However it relies on a key such as a String which seems quite error prone and fragile.

I'd like a pattern that uses enum. They have lots of great features and are robust. I've tried to find a standard design pattern for this but have drawn a blank. So I've come up with my own but I'm not terribly happy with it.

The pattern I'm using is as follows (the interface is highly simplified here to make it readable):

interface Complex { 
    void method();
}

enum ComplexItem implements Complex {
    ITEM1 {
        protected Complex makeInstance() { return new Complex() { ... }
    },
    ITEM2 {
        protected Complex makeInstance() { return new Complex() { ... }
    };

    private Complex instance = null;

    private Complex getInstance() {
        if (instance == null) {
            instance = makeInstance();
        }
        return instance;
    }

    protected void makeInstance() {
    }

    void method {
        getInstance().method();
    }
}

This pattern has some very nice features to it:

  • the enum implements the interface which makes its usage pretty natural: ComplexItem.ITEM1.method();
  • Lazy instantiation: if the construction is costly (my use case involves reading files), it only occurs if it's required.

Having said that it seems horribly complex and 'hacky' for such a simple requirement and overrides enum methods in a way which I'm not sure the language designers intended.

It also has another significant disadvantage. In my use case I'd like the interface to extend Comparable. Unfortunately this then clashes with the enum implementation of Comparable and makes the code uncompilable.

One alternative I considered was having a standard enum and then a separate class that maps the enum to an implementation of the interface (using the standard multiton pattern). That works but the enum no longer implements the interface which seems to me to not be a natural reflection of the intention. It also separates the implementation of the interface from the enum items which seems to be poor encapsulation.

Another alternative is to have the enum constructor implement the interface (i.e. in the pattern above remove the need for the 'makeInstance' method). While this works it removes the advantage of only running the constructors if required). It also doesn't resolve the issue with extending Comparable.

So my question is: can anyone think of a more elegant way to do this?

In response to comments I'll tried to specify the specific problem I'm trying to solve first generically and then through an example.

  • There are a fixed set of objects that implement a given interface
  • The objects are stateless: they are used to encapsulate behaviour only
  • Only a subset of the objects will be used each time the code is executed (depending on user input)
  • Creating these objects is expensive: it should only be done once and only if required
  • The objects share a lot behaviour

This could be implemented with separate singleton classes for each object using separate classes or superclasses for shared behaviour. This seems unnecessarily complex.

Now an example. A system calculates several different taxes in a set of regions each of which has their own algorithm for calculting the taxes. The set of regions is expected to never change but the regional algorithms will change regularly. The specific regional rates must be loaded at run time via remote service which is slow and expensive. Each time the system is invoked it will be given a different set of regions to calculate so it should only load the rates of the regions requested.

So:

interface TaxCalculation {
    float calculateSalesTax(SaleData data);
    float calculateLandTax(LandData data);
    ....
}

enum TaxRegion implements TaxCalculation {
    NORTH, NORTH_EAST, SOUTH, EAST, WEST, CENTRAL .... ;

    private loadRegionalDataFromRemoteServer() { .... }
}

Recommended background reading: Mixing-in an Enum

like image 934
sprinter Avatar asked Sep 17 '14 23:09

sprinter


People also ask

Can we have methods in enum?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Why is enum Singleton better in Java?

Creation of Enum instance is thread-safe By default, the Enum instance is thread-safe, and you don't need to worry about double-checked locking. In summary, the Singleton pattern is the best way to create Singleton in Java 5 world, given the Serialization and thread-safety guaranteed and with some line of code enum.

When should we use enum in Java?

When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

What is enumeration in Java with example?

An enumeration (enum for short) in Java is a special data type which contains a set of predefined constants. You'll usually use an enum when dealing with values that aren't required to change, like days of the week, seasons of the year, colors, and so on.


Video Answer


2 Answers

This works for me - it's thread-safe and generic. The enum must implement the Creator interface but that is easy - as demonstrated by the sample usage at the end.

This solution breaks the binding you have imposed where it is the enum that is the stored object. Here I only use the enum as a factory to create the object - in this way I can store any type of object and even have each enum create a different type of object (which was my aim).

This uses a common mechanism for thread-safety and lazy instantiation using ConcurrentMap of FutureTask.

There is a small overhead of holding on to the FutureTask for the lifetime of the program but that could be improved with a little tweaking.

/**
 * A Multiton where the keys are an enum and each key can create its own value.
 *
 * The create method of the key enum is guaranteed to only be called once.
 *
 * Probably worth making your Multiton static to avoid duplication.
 *
 * @param <K> - The enum that is the key in the map and also does the creation.
 */
public class Multiton<K extends Enum<K> & Multiton.Creator> {
  // The map to the future.
  private final ConcurrentMap<K, Future<Object>> multitons = new ConcurrentHashMap<K, Future<Object>>();

  // The enums must create
  public interface Creator {
    public abstract Object create();

  }

  // The getter.
  public <V> V get(final K key, Class<V> type) {
    // Has it run yet?
    Future<Object> f = multitons.get(key);
    if (f == null) {
      // No! Make the task that runs it.
      FutureTask<Object> ft = new FutureTask<Object>(
              new Callable() {

                public Object call() throws Exception {
                  // Only do the create when called to do so.
                  return key.create();
                }

              });
      // Only put if not there.
      f = multitons.putIfAbsent(key, ft);
      if (f == null) {
        // We replaced null so we successfully put. We were first!
        f = ft;
        // Initiate the task.
        ft.run();
      }
    }
    try {
      /**
       * If code gets here and hangs due to f.status = 0 (FutureTask.NEW)
       * then you are trying to get from your Multiton in your creator.
       *
       * Cannot check for that without unnecessarily complex code.
       *
       * Perhaps could use get with timeout.
       */
      // Cast here to force the right type.
      return type.cast(f.get());
    } catch (Exception ex) {
      // Hide exceptions without discarding them.
      throw new RuntimeException(ex);
    }
  }

  enum E implements Creator {
    A {

              public String create() {
                return "Face";
              }

            },
    B {

              public Integer create() {
                return 0xFace;
              }

            },
    C {

              public Void create() {
                return null;
              }

            };
  }

  public static void main(String args[]) {
    try {
      Multiton<E> m = new Multiton<E>();
      String face1 = m.get(E.A, String.class);
      Integer face2 = m.get(E.B, Integer.class);
      System.out.println("Face1: " + face1 + " Face2: " + Integer.toHexString(face2));
    } catch (Throwable t) {
      t.printStackTrace(System.err);
    }
  }

}

In Java 8 it is even easier:

public class Multiton<K extends Enum<K> & Multiton.Creator> {

    private final ConcurrentMap<K, Object> multitons = new ConcurrentHashMap<>();

    // The enums must create
    public interface Creator {

        public abstract Object create();

    }

    // The getter.
    public <V> V get(final K key, Class<V> type) {
        return type.cast(multitons.computeIfAbsent(key, k -> k.create()));
    }
}
like image 73
OldCurmudgeon Avatar answered Sep 21 '22 02:09

OldCurmudgeon


Seems fine. I would make initialization threadsafe like this:

enum ComplexItem implements Complex {
    ITEM1 {
        protected Complex makeInstance() {
            return new Complex() { public void method() { }};
        }
    },
    ITEM2 {
        protected Complex makeInstance() {
            return new Complex() { public void method() { }}
    };

    private volatile Complex instance;

    private Complex getInstance() {
        if (instance == null) {
            createInstance();
        }
        return instance;
    }

    protected abstract Complex makeInstance();

    protected synchronized void createInstance() {
        if (instance == null) {
            instance = makeInstance();
        }
    }

    public void method() {
        getInstance().method();
    }
}

The modifier synchronized only appears on the createInstance() method, but wraps the call to makeInstance() - conveying threadsafety without putting a bottleneck on calls to getInstance() and without the programmer having to remember to add synchronized to each to makeInstance() implementation.

like image 38
Bohemian Avatar answered Sep 19 '22 02:09

Bohemian