0

I have a main thread in which I have defined a HashMap object. Now in main thread I am creating N threads. now each thread will append its result in main thread's HashMap object and terminate. I tried passing the HashMap object in constructor but when I do this each thread make a local copy of HashMap object and edits it. This change doesn't save in main thread's HashMap object. what do I do?

in my main class

ThreadParallel threads[] = new ThreadParallel[N];
HashMap<Integer, String> map = new HashMap<Integer, String>();
for(int i=0;i<N;i++)
{
 threads[i] = new ThreadParallel(map);
}

now in ThreadParallel class

public class ThreadParallel implements Runnable{

HashMap<Integer, String> map;
Thread t;

public ThreadParallel(HashMap<Integer, String> map) {
          this.map = map;
      t = new Thread(this);
      t.start();
}
@Override
public void run() {    
      // adding data
}

}
navalp3
  • 117
  • 3
  • 3
  • 8

4 Answers4

0

Not the best of design but how about making the map public and static in your main class and accessing it in the thread class. Also using the concurrentHashMap will eliminate the synchronization problems.

ThreadParallel threads[] = new ThreadParallel[N];
public static ConcurrentMap<Integer, String> map = new ConcurrentHashMap<Integer, String>();
for(int i=0;i<N;i++)
{
 threads[i] = new ThreadParallel(map);
}

ThreadParallel class

public class ThreadParallel implements Runnable{

Thread t;

public ThreadParallel() {
      t = new Thread(this);
      t.start();
}
@Override
public void run() {    

      // adding data by accessing the main class map in static way
      // something lik  MainClass.map.put(1,"test");
} 

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

You code is correct. ThreadParallel does not create a new HashMap but saves a reference to the main thread's HashMap.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

I don't really think threads are making a local copy, it happens that HashMap is no thread-safe, try replacing HashMap with ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap) this way:

ThreadParallel threads[] = new ThreadParallel[N];
Map<Integer, String> map = new ConcurrentHashMap<Integer, String>();
for(int i=0;i<N;i++) {
    threads[i] = new ThreadParallel(map);
}

and also change the code in the threads:

public class ThreadParallel implements Runnable{

    Map<Integer, String> map;
    Thread t;

    public ThreadParallel(Map<Integer, String> map) {
        this.map = map;
        t = new Thread(this);
        t.start();
    }

    @Override
    public void run() {    
        // adding data
    }

}

morgano
  • 17,210
  • 10
  • 45
  • 56
0

Unless you have some synchronization in you adding data block, you could experience much worse problems than this. Use ConcurrentHashMap for use from different threads simultaneously without need of further synchronization (and without any blocking on monitors).

Sethiel
  • 182
  • 6
  • 14