There is a scenario in my Application where a Thread under its run method while(true) condition does this OPeration .
Under its while true condition , it continuasally fetches information from a External Data Source(Memcache) , adds / removes content from it, depending on newly logged in or logged out users , and finally updates it back to Memcache .
Some Snipet of code
public class MonitoringThread extends Thread
{
public void run() {
while(true)
String response = Memcache.get("USERINFO");
// Some checks will be made on response and builds a new response and updates back to Memcache .
synchronized (response)
{
Memcache.set("USERINFO" , response) ;
}
}
}
My question is
-
I have kept a Synchronized block on a set operation (Is this correct ) or it should be done while doing a get Operation ??
-
And the parameter that is passed to the Synchronied block , whether this should be this (the class itself) or the String response
Some more information .
Our Application runs on 5 Web Server instances controlled by a Load Balancer . ( All these 5 Instances will do that get Operation and Updates Data back )
Please share your ideas .
Thanks for reading , have a great day .
Edited Part
Thanks for the response ,
I have changed the synchronized block parameter , please let me know what is fesable appproach below
Option 1
Using synchronied block in the Thread
synchronized (Memcache.class)
{
Memcache.set("USERINFO" , response) ;
}
class Memcache
{
public static boolean set(String key, Object value) {
MemcacheClient.set(key, 0, value);
}
Or
Using Synchronied block in the Memcache class itself
class Memcache
{
synchronized (Memcache.class)
{
public static boolean set(String key, Object value) {
MemcacheClient.set(key, 0, value);
}
// other methods
}
I don’t know what you’re trying to do with this synchronized block, and why you need synchronization in the first place. What is the shared state that you want to protect with a synchronized block?
Anyway, what’s sure is that this snippet doesn’t make much sense.
synchronized(response)means that two threads won’t be able to execute the synchronized block if they both received the same String instance (the same object, not just the same characters) from the cache. This is very unlikely, and is probably not what you want.