Which One is optimal to choose ?

Syncronized hash map or Hash table with single thread model?

How can a hash map syncronized with out using syncrozed
blocks in programm?

Answer Posted / ranganathkini

The java.util.Hashtable provides a synchronized collection
implementation to store key-value pairs. Hence
synchronization of a Hashtable is not necessary.

Synchronization has a performance overhead and therfore must
be used with caution in only those situations where a
resource(s) is shared by multiple threads. Hence a
java.util.HashMap implementation can be used for single
threaded model and it can be externally synchronized if it
is to be used in a mult-threaded model.

To get a synchronized version of a java.util.HashMap without
using synchronized blocks, do this:

// make sure this is in imports
import java.util.*;

// our unsynchronized map object
Map myMap = new HashMap();

// get a synchronized map from our unsynchronized map
Map mySyncMap = Collections.synchronizedMap( myMap );

After this, all access to the map must be via mySyncMap
reference and NOT myMap.

Another way to acquire a synchronized map is:

Map mySyncMap = Collections.synchronizedMap( new HashMap() );

Is This Answer Correct ?    5 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why deletion in linkedlist is fast than arraylist?

537


What is identifier with example?

580


What do you mean by platform independence of Java?

538


What is the purpose of lambda expressions?

586


How many types of threads are there in java?

506






What does indexof mean?

537


How does finally block differ from finalize() method?

589


What is meant by polymorphism?

541


Can a constructor be made final?

669


What does system.gc() and runtime.gc() methods do?

602


What things should be kept in mind while creating your own exceptions in java?

634


How is string immutable in java?

545


Is java written in c?

548


Explain different ways of creating a thread. Which one would you prefer and why?

579


What is java ceil?

574