Synchronize("Cache_Group") part gets skipped , why is it so? Synchronize("Cache_Group") part gets skipped , why is it so? android android

Synchronize("Cache_Group") part gets skipped , why is it so?


sychronized("Cache_Group")

First thing that comes to mind is that sychronizing on a string is useless.

sychronized locks access to a block based on the given reference not the value. Using a "String" defeats this purpose because strings are immutable and calling synchronized("Cache_Group") twice will construct 2 strings with 2 different references, allowing the second iteration to break the intended lock.

EDIT: @see ReentrantLock for better access control


if your doing something like this:

sychronized("Cache_Group")

then your creating a string every time you want to syncronize which means your syncronizing different Objects every time, what you need is to syncronize one variable between functions

example:

public class test{    final Object lock = new Object;    public void apple(){        sychronized(lock ){            ...        }    }    public void orange(){        sychronized(lock ){            ...        }    }}

TIP: example above shows locking inside a class, if you want to lock between classes then your lock Object should be static/ above these classes or global, but beware from deadlocking your self!