4 ms·
Why synchronized block are not preemptible? When compiling public void syncMethod() { synchronized(lock) { // some code } } they
by skyde 3y ago
Why synchronized block are not preemptible?
When compiling
public void syncMethod() {
synchronized(lock) {
// some code
}
}
they could translate to
public void syncMethod() {
await reentrantLockAsync.lockAsync();
try {
await somecodeAsync();
} finally {
await lock.unlockAsync()
}
}
- dikei 3y agoThe first issue is your second code is not Java (no await/async literal for Java yet) The second issue is they're not completely equivalent. In the second case, you'd need extra memory for the `reentrantLock`, while `synchronized` works with any object. Furthermore, if you need to use `wait/notify`, then there need to be an extra `Condition` object to use in combination with the `ReentrantLock`. For sure, developers can rewrite most `synchronized` to use `ReentrantLock` and `Condition`, but javac won't do it automatically for you.
- skyde 3y agoThey could at least introduce a new language construct like await synchronizedAsync(lock) { // some code } C# introduced: await foreach (int item in RangeAsync(10, 3)) Console.Write(item + " "); // Prints 10 11 12 So you dont have to type: IAsyncEnumerator<int> e = RangeAsync(10, 3).GetAsyncEnumerator(); try { while (await e.MoveNextAsync()) Console.Write(e.Current + " "); } finally { if (e != null) await e.DisposeAsync(); }