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

In java, how many ways you can take input from the console?

745


Differentiate between stringbuffer and stringbuilder in java.

754


What is the right data type to represent a price in java?

757


What is thread pool? How can we create thread pool in java?

839


Can you override private or static method in java?

758


What is try-with-resources in java?

852


Can we serialize singleton class?

770


Why is inheritance used in java?

831


How to display names of all components in a Container?

2700


What does this () mean in java?

750


Why do we use string?

779


What are the main concepts of oops in java?

1111


How many threads does a core java have?

777


Distinguish between a predicate and a function?

773


Explain importance of inheritance in java?

782