Highly competitive cache access

Suppose I have two threads (Thread1, Thread2), where the threads access the cache for this object, for example, in the code below almost at the same time:

    Dim expensiveToGetData = Cache("ExpensiveDataKey")

    If ExpensiveToGetData is nothing then
'because the cache has expired

ExpensiveToGetData = LoadExpensiveDataFromDataSource()
       Cache("ExpensiveDataKey") = ExpensiveToGetData
    end If

    ProcessExpensiveData(ExpensiveToGetData)

Is it not possible for both threads to load the cache because they both requested data from the cache that was nothing / expired? I conducted several tests on the local computer, and it seems that the cache loads more than once. Is this a normal template?

+3
source share
2 answers

, , , , , , . , .

- , :

Dim expensiveToGetData = Cache("ExpensiveDataKey")

If ExpensiveToGetData is nothing then
    SyncLock yourLockObject /* YourLockObject should be a Shared object. */
        expensiveToGetData = Cache("ExpensiveDataKey")
        If expensiveToGetData Is Nothing Then
            ExpensiveToGetData = LoadExpensiveDataFromDataSource()
            Cache("ExpensiveDataKey") = ExpensiveToGetData
        End If
    End SyncLock
end If

ProcessExpensiveData(ExpensiveToGetData)

, , , . , , , .

+2

, , . , . , , .

+2

Source: https://habr.com/ru/post/1775286/


All Articles