Reputation: 175
Is there any problem with below code?
I want to use the method parseDateToInteger in a process that execute million times. This process can be accessed in multithread way, so I synchronized the method. I avoid to create the Calendar instance inside the method, cause its take a precious time. But I don't sure about this code behaviour. There are any problem in use this code?
private static final Calendar CALENDAR_BRASIL = GregorianCalendar.getInstance(LOCALE_BRASIL);
public synchronized static int parseDateToInteger(Date data) {
CALENDAR_BRASIL.setTime(data);
int ano = CALENDAR_BRASIL.get(Calendar.YEAR);
int mes = CALENDAR_BRASIL.get(Calendar.MONTH)+1;
int dia = CALENDAR_BRASIL.get(Calendar.DATE);
return ano * 10000 + mes * 100 + dia;
}
EDIT: I See this article that makes me afraid, but the author don't used a synchronized method.
http://blog.bielu.com/2008/08/javautilcalendar-confusion-is-it-safe_28.html
Upvotes: 1
Views: 49
Reputation: 7511
This is a bad idea. Although you've avoided creating all of those objects, you now have a method that can only be used by one object at a time. So instead of creating a million objects, partially in parallel, you're going to have processes that have to wait their turn to use the Calendar.
Just create the instance for each thread.
Upvotes: 1