How works a synchronisation of some object in a nutshell.
My goal is to synchronise a block of code by some string which is a parameter of a function.
At the begging I wasn't sure how synchronisation mechanism works. Is it using equals and hash code to compare object or memory address where object is allocated.
So synchronisation doesn't use equal method but memory address where object is allocated to.
So how to synchronise part of code when I have many instances of the same object (ex. string)?
A solution is to use some container for synchronized objects and retrieves instance of that object to use it to synchronization. In this case the best choose is map where it is possible to find object by key and get its value or if it not exists yet, add it.
So we need some kind of cache but how to manage this cache? We need only object instance when the synchronisation block is executed.
I think the easiest way on a single jvm is to use a weak reference. In this case I create a cache manager with WeakHashMap. The manager has a synchronized method findOrAdd and returns an instance of string object included to map.
What is important the WeakHashMap use weak reference only for key object so it is required to put as a value a WeakReference instance with my object.
My goal is to synchronise a block of code by some string which is a parameter of a function.
At the begging I wasn't sure how synchronisation mechanism works. Is it using equals and hash code to compare object or memory address where object is allocated.
So synchronisation doesn't use equal method but memory address where object is allocated to.
So how to synchronise part of code when I have many instances of the same object (ex. string)?
A solution is to use some container for synchronized objects and retrieves instance of that object to use it to synchronization. In this case the best choose is map where it is possible to find object by key and get its value or if it not exists yet, add it.
So we need some kind of cache but how to manage this cache? We need only object instance when the synchronisation block is executed.
I think the easiest way on a single jvm is to use a weak reference. In this case I create a cache manager with WeakHashMap. The manager has a synchronized method findOrAdd and returns an instance of string object included to map.
What is important the WeakHashMap use weak reference only for key object so it is required to put as a value a WeakReference instance with my object.
Map map = new WeakHashMap();Now, if instance of myString hasn't any reference to any other object or is not used to synchronisation, it will be removed from memory so removed from map as well.
map.put(myString, new WeakReference(myString));
No comments:
Post a Comment