File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes when the HashMap instance need synchronized? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "when the HashMap instance need synchronized?" Watch "when the HashMap instance need synchronized?" New topic
Author

when the HashMap instance need synchronized?

shi yongfei
Greenhorn

Joined: Nov 13, 2002
Posts: 7
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

Joined: Jun 02, 2003
Posts: 7
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

Joined: Dec 11, 2001
Posts: 10
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

Joined: Jan 30, 2000
Posts: 18670
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.


"I'm not back." - Bill Harding, Twister
Dana Hanna
Ranch Hand

Joined: Feb 28, 2003
Posts: 227
******** 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.
 
I agree. Here's the link: http://jrebel.com/download
 
subject: when the HashMap instance need synchronized?
 
Similar Threads
class level lock and object level lock
Synhronization
static initialization block?
When to use Hashmap (synchronized as needed) and when to use Concurrent hashmap?
create a new HashMap from a HashMap entries of other methods