-1

I am a beginner learning Java. Now I have a question, could someone help me solve it? :)

I have a class named Server which maintains a hashmap variable, and I it has two methods named send() and receive(). I want the two methods to run concurrently. The send() method will use the hashmap variable and the receive() method will change the hashmap variable.

Please help work it out. Thanks a lot!

5 Answers5

1

You can use Collections.synchronizedMap(new HashMap());

Edit 1: code template

public class Server
{
    private static Map<String,String> map = Collections.synchronizedMap(new HashMap<String, String>());

    public void send()
    {
        //
        // Do some operation using map variable
    }

    public void receive()
    {
        // change the map variable as you want
        //
    }
}
prasanth
  • 3,502
  • 4
  • 28
  • 42
1

Define the HashMap in the main thread that spawns the send and receive threads. Make sure you use a SynchronizedMap so that you don't run into race condition.

Harshal Pandya
  • 1,622
  • 1
  • 15
  • 17
0

Items are shared by default. What you'll need is some form of lock or mutex to control sharing and prevent the two threads from trying to modify it at the same time.

Or, you can just use ConcurrentHashMap

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
0

There are two solutions, simplest one is to use thread safe hashmap i.e. ConcurrentHashMap. You need not to worry about the synchronization issues as JVM will take care of it. It will be good to go through the Javadoc for the same:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html

Other way is to synchronize the send() and receive()methods or the portion of the methods where you update the hashmap.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

Use COncurrentHashMap

It allows concurrent modification of the Map from several threads without the need to block them.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307