I was asked by the interviewer about disadvantages of using thread safe class like Hashtable in single threaded environment? Are there any disadvantages? if not then why are there non thread safe class introduced later?
I was asked by the interviewer about disadvantages of using thread safe class like Hashtable in single threaded environment?
There are, although most of the disadvantages are around performance. Even single-threaded environments have multiple threads in them (think GC, finalizers, signal handlers, JMX, etc.) so the language still needs to obey the synchronization constructs such as synchronized
, volatile
, and the native lock implementations. These language features flush or invalidate memory caches and affect code reordering both of which can dramatically affect overall runtime performance.
if not then why are there non thread safe class introduced later?
Non-thread-safe objects always perform better than their thread-safe counterparts in either single or multi-threaded applications. The ability to deal with local CPU cached memory is one of the main speed increases provided by modern hardware. If you don't have to reach out to the main memory bus, you can execute operations orders of magnitude faster. Synchronization constructs decrease the ability of cache memory to be used.
Lastly, thread-safe classes are typically more complicated both in terms of the data structures involved as well as the logic necessary for them to operate correctly in a multi-thread application. This means that even if we ignore the synchronization constructures, it may use more memory and run slower, although the degree to which this is the case is very dependent on the particular class in question