'How java synchronized object actually works
If I have a code like this one, called by different threads each time, is there a race condition in the order of the calls? more specific will synchronized() be executed right away once I call methodA() ? or there is a delay between method call and synchronized block that can produce a race condition between calls?
final Object lock = new Object();
StringBuilder sb = new StringBuilder();
public void methodA(String str)
{
// empty
synchronized(lock)
{
sb.append(str);
}
}
Again, my question is if there can be a delay between the call and the synchronized block. I am synchronizing other parts of code with the same lock object in other methods as well. But what I want to ensure is that calls of the methodA() from different threads will never produce a race condition right after call and before synchronized block and how to achieve that.
is the solution the code that follows? does synchronized methodName keyword synchronize with synchronized(this) in the second method ?
Is synchronized methodName like synchronized(this) but without delay between the call and synchronize keyword ?
also if I call the synchronized methodA from one thread and in parallel from another thread the synchronized methodB will they wait each other ?
public class Test
{
StringBuilder sb = new StringBuilder();
public synchronized void methodA(String str)
{
sb.append(str);
}
public synchronized void methodB(String str)
{
sb.append(str);
}
public void someOtherMethod()
{
// some code here
// some more code here
synchronized(this)
{
// will synchronize with methodA and/or B?
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
