[ 
https://issues.apache.org/jira/browse/ZOOKEEPER-955?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12968875#action_12968875
 ] 

Henry Robinson commented on ZOOKEEPER-955:
------------------------------------------

Hi Thomas - 

Nice thought - definitely worth checking out. Please do benchmark this, however 
-  it is not completely clear cut which is the better synchronization 
primitive. 

Atomic* objects usually call into a system-specific compare and swap method, 
usually (on x86) a CMPXCHG instruction which locks the bus whether or not the 
compare is successful. This is probably the same hardware synchronization 
primitive that Java's thin locks use.

Java locks are usually some form of thin locks, at least in HotSpot [1], which 
are locks that are fast in the uncontended case - they are just as fast as CAS 
on words. In the contended case, the lock is inflated which is a one-time 
spinning step, after which it is a OS-based mutex which we would expect to be 
slower than Atomic primitives in general. However, when lock contention is very 
high, you might find that synchronized blocks perform better as optimistic 
locking implies a busy wait loop when a lock can't be taken.

Henry

[1] http://wikis.sun.com/display/HotSpotInternals/Synchronization



> Use Atomic(Integer|Long) for (Z)Xid
> -----------------------------------
>
>                 Key: ZOOKEEPER-955
>                 URL: https://issues.apache.org/jira/browse/ZOOKEEPER-955
>             Project: ZooKeeper
>          Issue Type: Improvement
>          Components: java client, server
>            Reporter: Thomas Koch
>            Assignee: Thomas Koch
>            Priority: Trivial
>         Attachments: ZOOKEEPER-955.patch
>
>
> As I've read last weekend in the fantastic book "Clean Code", it'd be much 
> faster to use AtomicInteger or AtomicLong instead of synchronization blocks 
> around each access to an int or long.
> The key difference is, that a synchronization block will in any case acquire 
> and release a lock. The atomic classes use "optimistic locking", a CPU 
> operation that only changes a value if it still has not changed since the 
> last read.
> In most cases the value has not changed since the last visit so the operation 
> is just as fast as a normal operation. If it had changed, then we read again 
> and try to change again.
> [1] Clean Code: A Handbook of Agile Software Craftsmanship (Robert C. Martin) 

-- 
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online.

Reply via email to