"how to make a shared resource thread-safe when using dependency injection?" Code Answer

4

cflock only prevents code from executing if every occurrence is locked the same way.

for example:

page1.cfm

<cflock type="exclusive" scope="server" timeout="10" >
   <cfset application.xyz = 'abc'>
</cflock>

page2.cfm

<cfset application.xyz = '123'>

page2.cfm is going to negate any locks you have on page1.cfm if page2 runs the same time page1 does. that said, it's good that you are locking inside your cfc so that each object doesn't have to be locked.

however, locking every occurrence isn't enough. the following won't do much good either.

page1.cfm

<cflock type="exclusive" scope="server" timeout="10" >
   <cfset application.xyz = 'abc'>
</cflock>

page2.cfm

<cflock type="exclusive" scope="server" timeout="10" >
   <cfset application.xyz = '123'>
</cflock>

this will halt the processing for every request of page1 and page2 but will not protect application.xyz on page1 from changes made to application.xyz on page2. to do this you need to give your locks a "name".

locks name. mutually exclusive with the scope attribute. only one request can execute the code within a cflocktag with a given name at a time. cannot be an empty string.

permits synchronizing access to resources from different parts of an application. lock names are global to a coldfusion server. they are shared among applications and user sessions, but not clustered servers.

because you are creating multiple instances of your object, i believe servermemorymanagerobject could interfere with servermemorymanagerobject2 unless you name your lock.

here is some more information about locking dos and don'ts

  • locking code with cflock
  • cflock and negative outcomes think it through
  • cfmythbusters - countering some conventional wisdom
By daoliker on February 15 2022

Answers related to “how to make a shared resource thread-safe when using dependency injection?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.