[concurrency-interest] SynchronizedLong vs. other locks

Joe Bowbeer joe.bowbeer at gmail.com
Fri Jul 8 12:09:14 EDT 2005


One option would be to retain "tomorrow" as a Calendar and synchronize on that:

private static long getTomorrowTime() {
    synchronized (tomorrow) {
        long tomorrowMillis = tomorrow.getTimeMillis();
        if (System.currentTimeMillis() > tomorrowMillis) {
            tomorrow.add(Calendar.DATE, 1);
            tomorrowMillis = tomorrow.getTimeMillis();
        }
        return tomorrowMillis;
    }
}


NOTE: I'm suspicious of any use of the GregorianCalendar implementation.

See gotchas and possible alternative:

http://mindprod.com/jgloss/calendar.html
http://mindprod.com/jgloss/gotchas.html#DATE
http://mindprod.com/products1.html#BIGDATE


On 7/8/05, Aleksey Gureev <spyromus at noizeramp.com> wrote:
> Hi,
> 
> I have a following piece of code:
> 
> ---
>     private static synchronized long getTomorrowTime()
>     {
>         final long current = System.currentTimeMillis();
>         if (current > tomorrow)
>         {
>             GregorianCalendar cal = new GregorianCalendar();
>             cal.add(Calendar.DATE, 1);
>             cal.set(Calendar.HOUR_OF_DAY, 0);
>             cal.set(Calendar.MINUTE, 0);
>             cal.set(Calendar.SECOND, 0);
>             cal.set(Calendar.MILLISECOND, 0);
>             tomorrow = cal.getTimeInMillis();
>         }
> 
>         return tomorrow;
>     }
> ---
> 
> "tomorrow" is static. It's obvious that the instance synchronization is
> not really what's necessary because the other objects of this class can
> still introduce race conditions. My question is can SynchronizedLong
> help me somehow or it's better to replace instance locking with
> class-wide locking?
> 
> Thank you,
> 
> Aleksey Gureev
> Noizeramp Creative Group
> http://www.noizeramp.com/
>



More information about the Concurrency-interest mailing list