Locking Objects

LockManager.cs
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02using System; 03using Db4objects.Db4o; 04using Db4objects.Db4o.Ext; 05 06namespace Db4objects.Db4odoc.Semaphores 07{ 08 /** 09 * This class demonstrates a very rudimentary implementation 10 * of virtual "locks" on objects with db4o. All code that is 11 * intended to obey these locks will have to call lock() and 12 * unlock(). 13 */ 14 public class LockManager 15 { 16 17 readonly private string SemaphoreName = "locked: "; 18 readonly private int WaitForAvailability = 300; // 300 milliseconds 19 20 readonly private IExtObjectContainer _objectContainer; 21 22 public LockManager(IObjectContainer objectContainer) 23 { 24 _objectContainer = objectContainer.Ext(); 25 } 26 27 public bool Lock(object obj) 28 { 29 long id = _objectContainer.GetID(obj); 30 return _objectContainer.SetSemaphore(SemaphoreName + id, WaitForAvailability); 31 } 32 33 public void Unlock(Object obj) 34 { 35 long id = _objectContainer.GetID(obj); 36 _objectContainer.ReleaseSemaphore(SemaphoreName + id); 37 } 38 } 39 40}
LockManager.vb
01' Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com 02Imports System 03Imports Db4objects.Db4o 04Imports Db4objects.Db4o.Ext 05 06Namespace Db4objects.Db4odoc.Semaphores 07 ' * 08 ' * This class demonstrates a very rudimentary implementation 09 ' * of virtual "locks" on objects with db4o. All code that is 10 ' * intended to obey these locks will have to call lock() and 11 ' * unlock(). 12 ' */ 13 Public Class LockManager 14 15 Private ReadOnly SEMAPHORE_NAME As String = "locked: " 16 Private ReadOnly WAIT_FOR_AVAILABILITY As Integer = 300 ' 300 milliseconds 17 18 Private ReadOnly _objectContainer As IExtObjectContainer 19 20 Public Sub New(ByVal objectContainer As IObjectContainer) 21 _objectContainer = objectContainer.Ext() 22 End Sub 23 24 Public Function Lock(ByVal obj As Object) As Boolean 25 Dim id As Long = _objectContainer.GetID(obj) 26 Return _objectContainer.SetSemaphore(SEMAPHORE_NAME + id.ToString(), WAIT_FOR_AVAILABILITY) 27 End Function 28 29 Public Sub Unlock(ByVal obj As Object) 30 Dim id As Long = _objectContainer.GetID(obj) 31 _objectContainer.ReleaseSemaphore(SEMAPHORE_NAME + id.ToString()) 32 End Sub 33 End Class 34 35End Namespace