I am trying to use synchronized block for my use-case where I need to use it on following code.
public void saveInCatch(String reqId,String desc) {
synchronized (reqId) {
cache.add(reqId,desc);
}
}
This method is getting called from many places in my application. I want to make sure that the code block should be accessed by only one thread at a time if the reqId
is same. If it is different then this block can be accessed concurrently. How can I achieve this?
CodePudding user response:
You are looking when one thread is wiritting still another thread should be able to read it
I think that would be tricky to do. Since the value should be flushed out to memory.
Check the link for similar question
Java Threads: synchronized reading and writing of value on the same object
CodePudding user response:
The synchronized block works on the instance Id of the object you are matching
so with your code I can create two strings
String id1 = "1234";
String id2 = "1234";
If two threads call your function using different variables containing the same Id then they will not get blocked, they will both run.
If you really want to sychronize on a string like that you should create static final String objects for every possible Id
Note: if you decide to use a numeric type like Integer for you sync object then you might find it works for low numbers and then stops working as numbers get higher as Java uses a table of Ints so that only one version of 1 will be created for your code, but every instance of 9999 might have a unique object Id