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

Dawid Kurzyniec dawidk at mathcs.emory.edu
Fri Jul 8 10:11:51 EDT 2005


Dawid Kurzyniec wrote:

> 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:
>
Actually, sorry, in your case, the potential race is rather harmless 
since the same value would be written anyway (unless a thread is 
preempted for more than 24h). So in fact, you could drop the 
synchronization, and you don't even need atomic variables, just make 
"current" volatile. But I still think that the version without a shared 
variable will be the fastest.

Regards,
Dawid



More information about the Concurrency-interest mailing list