0

Does Velocity support server-side atomic updates ? I'm trying to see if i can port some code (based on memcached) which implemented a ring buffer based on memcache's INCR operation.

JBland
  • 1,263
  • 10
  • 13

1 Answers1

3

I can't say that I'm familiar enough with memcached to know exactly what you mean, but I'm assuming that it involves locking a cached item so that one client can update it, which is supported by Velocity through the GetAndLock and PutAndUnlock methods.

Edit: OK, now I understand what you mean, no I haven't seen anything like that in Velocity. But you could write it as an extension method e.g.

Imports System.Runtime.CompilerServices

Public Module VelocityExtensions

<Extension()> _
Public Sub Increment(ByVal cache As Microsoft.Data.Caching.DataCache, ByVal itemKey As String)

    Dim cachedInteger As Integer
    Dim cacheLockHandle As DataCacheLockHandle

    cachedInteger = DirectCast(cache.GetAndLock(itemKey, New TimeSpan(0, 0, 5), cacheLockHandle), Integer)

    cachedInteger += 1

    cache.PutAndUnlock(itemKey, cachedInteger, cacheLockHandle)

End Sub

<Extension()> _
Public Sub Decrement(ByVal cache As Microsoft.Data.Caching.DataCache, ByVal itemKey As String)

    Dim cachedInteger As Integer
    Dim cacheLockHandle As DataCacheLockHandle

    cachedInteger = DirectCast(cache.GetAndLock(itemKey, New TimeSpan(0, 0, 5), cacheLockHandle), Integer)

    cachedInteger -= 1

    cache.PutAndUnlock(itemKey, cachedInteger, cacheLockHandle)

End Sub

End Module

Your usage would then become:

Imports VelocityExtensions
Imports Microsoft.Data.Caching

Partial Public Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim myCache As DataCache
    Dim factory As DataCacheFactory

    myCache = factory.GetCache("MyCacheName")

    myCache.Increment("MyInteger")

End Sub

End Class
PhilPursglove
  • 12,511
  • 5
  • 46
  • 68
  • In memcached you can do atomic increments and decrements in a single server roundtrip. For example, i can do a client.Increment("totalViews-" + contentId), which does the lock/increment/unlock on the server in one go. – JBland Oct 14 '09 at 15:16
  • Thanks for that, Phil. It definitely works, though not as efficient as id like. – JBland Oct 14 '09 at 18:36
  • This solution wouldn't work because the second call to the lock will fail. – Eugeniu Torica Jun 07 '11 at 08:17
  • By failure I mean that request won't be blocked which will create miss update problem. Link here http://msdn.microsoft.com/en-us/library/dd631073.aspx – Eugeniu Torica Jun 07 '11 at 08:22