Sourabh
Sourabh

Reputation: 429

Collections.SynchronizedList implementation - synchronized method vs mutex

The implementation of methods in java.util.Collections.SynchronizedList is using synchronization on a mutex. Given that in all the methods, the complete method body is under the synchronized block, why couldn't it be written as synchronized methods?

Basically:

public boolean doSomething(Collection<?> coll) {
    synchronized (mutex) {return c.doSomething(coll);}
}

vs.

public synchronized boolean doSomething(Collection<?> coll) {
    return c.doSomething(coll);
}

I didn't scan all the classes, but may be the reason is that somewhere some method needs partial synchronization (i.e. not the whole method body), and because of them extending the same base class (SynchronizedCollection), the implementation happened to be using mutex to have that finer control. Is that correct? or is there any other reason, like performance, for this choice of implementation?

Upvotes: 0

Views: 504

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

why couldn't it be written as synchronized methods?

There is a package-private factory method for SynchronizedList and corresponding package-private constructor which allows the list to be constructed with a mutex other than the list itself.

You can't use it directly, but there will be usages of it within the java.util package.

One example is in SynchronizedList.subList:

    public List<E> subList(int fromIndex, int toIndex) {
        synchronized (mutex) {
            return new SynchronizedList<>(list.subList(fromIndex, toIndex),
                                        mutex);
        }
    }

i.e. accesses to the sublist are synchronized on the parent list, not the sublist.

Another example is Vector.subList method:

public synchronized List<E> subList(int fromIndex, int toIndex) {
  return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                                      this);
}

i.e. accesses to the sublist are synchronized on the Vector, not the sublist.

Upvotes: 2

Related Questions