views:

347

answers:

4

The questions says it all, just wondering, in an interview, what would you say when they ask you, "What does it practically mean by Hashtable or Vectors being synchronized?"

+7  A: 

Practically it means two things:

  1. Don't use them unless you will be sharing them between threads (if not just use HashMap or ArrayList).
  2. If you are sharing them between threads, check that the synchronization policies they implement actually are sufficient to make your program threadsafe (because the existence of some synchronization is little indication of the all-round concurrent behaviour of a class).
jjujuma
wow this is such a good explanation +1
c0mrade
+1  A: 

It means that the access to the underlying array/collection (add, get, set, put, remove, etc..etc..) is all synchronized. It cannot take place simultaneously. Virtually, all access is been laid out in a first-in-first-out (FIFO) queue. Only and if only if there's nobody (read: no other thread) who's currently accessing the object, then the next (thread) in queue may access it.

BalusC
Multiple threads can however hold a reference to a synchronized collection, correct? It's just that only one of those threads may (add, get, set, put, remove, etc..etc..) at the same exact time, correct?
Marcus
That's correct. The synchronization is in the *access*.
BalusC
'first-in-first-out (FIFO) queue'. No. Queueing isn't specified. It is unspecified who gets the next access: probably the highest-priority waiting thread.
EJP
A: 

Only one thread of execution can change the state of the container at any given time.

If the container was not synchronised, multiple thread of execution could try to change the state of the container at the same time. This would of course most likely end up with the internal state of the container being corrupted, i.e. not what you want.

The original Java containers, e.g. java.util.Vector and java.util.Hashtable, were all synchronised for safety reasons. But the downside of synchronising access as a default is that use cases where synchronisation is not necessary will suffer the performance penalty of synchronisation. So now Java ships with unsynchronised containers as well, e.g. ArrayList and HashMap.

liwp
A: 

It means that only one thread may access it at a time.

This may be a problem if you use it in a program that uses only a thread , because the process of checking who owns the monitor ( which thread tries to use it ) will still be performed wasting valuable processing time.

Even using them with one or more thread may be less performant than using an unsynchronized version and synchronizing only the dengerous parts.

OscarRyz