[concurrency-interest] Re: SynchronizedLong vs. other locks

Dawid Kurzyniec dawidk at mathcs.emory.edu
Fri Jul 8 09:58:25 EDT 2005


Aleksey Gureev wrote:

>Actually, it is already class-wide, sorry, but anyway, any help from
>SynchronizedLong?
>  
>
>>---
>>    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?
>>
>>    
>>
Not really, since you have "read-modify-write" operation; you need the 
lock if you want to keep it in a shared variable. But why not just do:

private static final long DAY = 24*60*60*1000;

private static long getTomorrowTime() {
    return (((System.currentTimeMillis() + DAY)/DAY)*DAY;
}

I bet this will be much faster than synchronization.



More information about the Concurrency-interest mailing list