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

What is multi level inheritance in java?

551


How to display all the prime numbers between 1 and n (n is the number, get the input from user)

505


What are untrusted applets?

582


Tell us something about different types of casting?

511


What is the use of volatile in java?

592






What is the difference between interface & abstract class?

551


Implement 2 stacks with just 1 array. The stack routines must not indicate overflow unless every slot in array is used.

825


Is string pool garbage collected?

538


How do you compare values in java?

533


Differentiate between postfix and prefix operators in java.

633


Why parameters should be passed by reference?

490


What is a numeric string?

558


How does queue work in java?

521


What is sortedset in java?

562


Is java se open source?

560