Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can we do about java.util.Calendar constructor synchronizing on a static Hashtable?

I was horrified to see many of our app threads competing to synchronize on a java.util.Hashtable.get(xx) method that gets accessed from the Calendar's constructor.

at java.util.Hashtable.get(java.lang.Object)
at java.util.Calendar.setWeekCountData(java.util.Locale)
at java.util.Calendar.<init>(java.util.TimeZone, java.util.Locale)
at java.util.GregorianCalendar.<init>(java.util.TimeZone, java.util.Locale)

The ctor looks up a static hashtable that is meant to be serve as a cache, but ends up blocking all threads.

/**
 * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
 * of a Locale.
 */
private static Hashtable<Locale, int[]> cachedLocaleData = new Hashtable<Locale, int[]>(3);

protected Calendar(TimeZone zone, Locale aLocale)
{
    .. .. snip .. 
    setWeekCountData(aLocale);
}

private void setWeekCountData(Locale desiredLocale)
{
/* try to get the Locale data from the cache */
int[] data = cachedLocaleData.get(desiredLocale);

....
}

Is there a better way to manipulate dates? Does Joda bypass all these issues?

like image 818
Ashwin Jayaprakash Avatar asked Nov 11 '11 23:11

Ashwin Jayaprakash


1 Answers

Better solution, use Java 7, the Hashtable has been replaced by a ConcurrentMap.

like image 143
Emmanuel Bourg Avatar answered Oct 15 '22 09:10

Emmanuel Bourg