Lets suppose I have following mbean:
public interface ExampleMBean {
public float lastHourMean();
}
with following implementation:
import java.util.*;
public class Example implements ExampleMBean {
private Map<Date, Long> dates = new HashMap<Date, Long>();
@Override
public float lastHourMean() {
return calculateMean(getTimesFromLastHour(dates));
}
public void addDate(Date date, Long time) {
dates.put(date, time);
removeOldDates();
}
Map<Date, Long> getTimesFromLastHour(Map<Date, Long> dates) {
//return dates from last hour....
}
float calculateMean(Map<Date, Long> lastHourCalls) {
Collection<Long> values = lastHourCalls.values();
int n = values.size();
if (n > 0) {
long sum = 0L;
for (Long time : values) {
sum = sum + time;
}
return sum / values.size();
} else {
return 0;
}
}
public void removeOldDates() {
//...removes dates before one hour ago from a Map "dates"..
// to avoid buffer overflow
}
}
Mbean is registered as follow:
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("com.javacodegeeks.snippets.enterprise:type=Hello");
Example sampleBean = new Example();
mBeanServer.registerMBean(sampleBean,objectName);
Now, instance of this Mbean is used in many functions in multithreaded applications in this way:
sampleBean.addDate(new Date(), time);
The question is if a functions addDate(Date, Long) and removeOldDates are thread safe and if not - how to make this appliaction thread safe ?