2

Why did Sun not use synchronized(this) instead of mutex = this and then using synchronized(mutex) ?
I could not see any benefit doing of doing what they did ? Am I missing something ?

static class SynchronizedCollection<E> implements Collection<E>, Serializable {
        private static final long serialVersionUID = 3053995032091335093L;

        final Collection<E> c;  // Backing Collection
        final Object mutex;     // Object on which to synchronize

        SynchronizedCollection(Collection<E> c) {
            if (c==null)
                throw new NullPointerException();
            this.c = c;
            mutex = this;
        }
        SynchronizedCollection(Collection<E> c, Object mutex) {
            this.c = c;
            this.mutex = mutex;
        }

        public int size() {
            synchronized (mutex) {return c.size();}
        }
        public boolean isEmpty() {
            synchronized (mutex) {return c.isEmpty();}
        }
1
  • 1
    Try not to ask the quesion as "Why did Sun do this", because only the developers at Sun can answer that. Also, how would you verify that the answers you get are correct? As such, there may not be any "correct" answer to this question.
    – Patrick
    Oct 12, 2013 at 8:12

4 Answers 4

2

This allows the client of a Collection, via the second constructor, to synchronise multiple collections on a single mutex.

1

The provision to the client to pass his own mutex object gives a world of flexibility. The client can involve the synchronized collection in arbitrary locking schemes, covering as much code as appropriate for his use case. If this was the only option, then the lock granularity would be fixed to just one method call on the collection, or it would force the client to use the collection as his mutex, disrupting the overall design.

0

I think that gives you more safety when you want to synchronize on collection methods as well as in your implemented methods with single mutex. And may be you can synchronize between many such collections with only one mutex!

0

Take for example Collections.synchronizedMap(map).values(), which should be a Collection synchronized on the map mutex. There are lots of other utilities that need a Collection synchronized on some other object.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.