• Post Reply Bookmark Topic Watch Topic
  • New Topic

when the HashMap instance need synchronized?

 
shi yongfei
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
an class will be run under a mutilthreaded environ,the class like this
public class ReportEngine
{
private HashMap publicReport;
private Report getReportData(String reportKey) {
return publicReport.get(reportKey);
}
private void deleteReport(String reportKey) {
publicReport.remove(reportKey);
}
private void addReport(String reportKey,Report report) {
publicReport.add(reportKey,report);
}
}
So, what I am puzzled are:
1)which methods need synchronized ?
2)what will happen if don't synchronize any methods ?
 
Kao-Wei Wan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1)which methods need synchronized ?
Both deleteReport and addReport
2)what will happen if don't synchronize any
methods ?
your program may lost data or crush
 
Philip Hung
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also replace the HashMap with a Hashtable unless you specifically want a HashMap or you are permitting null values.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ugh. Let Hashtable die the death it deserves (along with Vector and Enumeration). There's no need for those things anymore; they just create additional opportunities for confusion, particularly for newbies. If you really want a synchronized Map, use Collections.synchronizedMap(new HashMap()). And pay attention to the warnings about iterating - these would have applied to Hashtable too.
 
Dana Hanna
Ranch Hand
Posts: 227
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
******** Use a synchronized HashMap - Collections.synchronizedMap(new HashMap());
Also - the get method would also have to be synchronized if for some reason you don't want a synchronized map (why not?). This is because the HaspMap could be resizing itself during the get operation and really throw it off.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!