What does it mean when we say Hashtable or Vector is synchronized?

后端 未结 4 866
借酒劲吻你
借酒劲吻你 2020-12-30 14:27

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?

相关标签:
4条回答
  • 2020-12-30 14:32

    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).
    0 讨论(0)
  • 2020-12-30 14:33

    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.

    0 讨论(0)
  • 2020-12-30 14:38

    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.

    0 讨论(0)
  • 2020-12-30 14:44

    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.

    0 讨论(0)
提交回复
热议问题