0

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 ?

user109447
  • 1,069
  • 1
  • 10
  • 20

1 Answers1

0

This is not thread-safe in any way or manner. Not only is interleaving possible, you're not even guaranteeing that any changes to the map are visible to other threads.

To make it thread-safe you may want to replace your map with a ConcurrentLinkedQueue, since what you've described is a lot more like a queue than a map. This will fix concurrency issues and also improve your performance, since it's already sorted.

Ordous
  • 3,844
  • 15
  • 25