What is the recommended approach to replacing a `s...
# android
g
I would say that (especially in context of Android, where you don’t want too block UI even because of locks) usually use coroutines Mutex, because anyway most of our business logic is suspend function based
But nothing wrong with usage of Java’s concurrency primitives like ReentrantLock
l
Yeah so I was thinking about a reentrantlock but how do I guarantee only one instance of that object is created
g
If you looking for replacement for synchronized block I don’t see a problem
synchronized already works only on object level, so it’s exactly the same as creating ReentrantLock as class-level property
l
so this is the code i'm trying to refactor which results in this logic potentially being executed in parallel
Copy code
val lockObject = StarPrinterManager.manager ?: Object()
synchronized(lockObject) {
  // code to be executed inside the lock, to prevent multiple resources from calling this code      
}
and as it stands now if the
StarPrinterManager.manager
there will be a new object instance created everytime it hits that condition
g
so lockObject just becomes ReentrantLock
Honestly I’m not that understand code snippet which you showed, if it a part of the same function, it doesn’t look that synchronization is correct
Usually you init lock on the class creation level to sync operation inside of your class. f you want global lock, just make declare it on top level, not as part of your class, so it will be a single lock per process of your application
đź‘Ť 1
l
Yes this code snippet is all inside a single function
g
Then it not syncronized correctly
Multiple threads may execute “code to be executed inside the lock” simultaneusly if StarPrinterManager.manager is null
l
So that's what I need to figure out, how do I declare it on the top level so it's a single lock per application?
g
single lock per application is just val myResourceLock = ReentrantLock()
l
But do I need to use dependency injection?
g
It’s up to you
l
Which class do I declare the reentrantlock instance?
g
If you use DI which supports Singleton correctly, sure
Usually you do not declare lock public and instead you create a class, some repository for your resource, make this class Singleton (using DI, or just kotlin object) And expose functions to work with this resource, which under the hood use lock
l
Okay I'll look into something like that
Was hoping to find some open source examples of this
g
Of what exactly?
l
Just that singleton pattern
g
Do you use DI library? If so, it probably should already support it. If not, use Kotlin object declaration
đź‘Ť 1
p
You can also try Kotlin Atomicfu
g
I wouldn't recommend atomicfu until you really know what you are doing, it's very low level and exists as building block for multiplatform synchronization.
204 Views