1

In Collections class, class SynchronizedMap has two constructors. One takes only a map instance and another with a map and a mutex.

    SynchronizedMap(Map<K,V> m) {
        this.m = Objects.requireNonNull(m);
        mutex = this;
    }

    SynchronizedMap(Map<K,V> m, Object mutex) {
        this.m = m;
        this.mutex = mutex;
    }

However, SynchronizedMap class is a private static class and only way to access it using provided wrapper method:

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
    return new SynchronizedMap<>(m);
}

As understood from this link, the idea of the second constructor to use user-supplied mutex other than this. Now, since the wrapper method is the only way to get an instance of SynchronizedMap (which takes only a map object) , what is the purpose of this second overloaded constructor?

Somnath Musib
  • 3,548
  • 3
  • 34
  • 47

1 Answers1

1

It is used e.g. in SynchronizedSortedMap which extends SynchronizedMap when creating submap view.

 public SortedMap<K,V> subMap(K fromKey, K toKey) {
            synchronized (mutex) {
                return new SynchronizedSortedMap<>(
                    sm.subMap(fromKey, toKey), mutex);
            }
        }

To share the same mutex.

Michal
  • 970
  • 7
  • 11