Java sync polling
Here is the code I saw once. Can you see what's wrong with him?
[updated]
public class ResourceManager1
{
private final String mutex = "";
Object resource = null;
public Object getResource()
{
synchronized (mutex)
{
if (resource == null)
{
resource = new Object();
}
}
return resource;
}
}
public class ResourceManager2
{
private final String mutex = "";
Object resource = null;
public Object getResource()
{
synchronized (mutex)
{
if (resource == null)
{
resource = new Object();
}
}
return resource;
}
}
0
source to share
3 answers
Never sync strings, in particular string literals that are interned. You basically only have one lock.
In general, never sync on any reference that might be visible outside of your class (including "this"), unless the target of external visibility is for blocking purposes. I usually use a variable private final
created exclusively for blocking.
+12
source to share