1

ロックがオブジェクト レベルになるまで正常に動作するコード スニペットを見つけ、同じロックが static final になると (つまり static キーワードが追加されると)、同時実行関連のエラーでコードが失敗し始めます。

オブジェクト レベルで機能するロックは、そのスコープが static になると再び機能する必要がありますか? ロックを静的にすることは、ロックをより制限的にするだけであり、オブジェクト レベルの場合よりも同時実行性の問題が発生し始めるべきではないと考えました。しかし、私は逆のことが起こっていることを発見しています。

4

2 に答える 2

1

Should a lock that works at object level reamin working once its scope is made static ?

If you move a lock from being an instance lock to be a static lock, it should not cause concurrency issues. You are correct that it should make the code more restrictive in that a single lock will be used instead of multiple instance locks. This is, of course, if the lock in question is static final and all of the places in your code are appropriately locking it.

public static final Object lockObject = new Object();

What may be happening is that moving the lock has uncovered a bug that was there previously but application timing was causing it to be hidden. By locking on a static lock (or on a static method) the timing of the threads in your application will most likely be significantly changed.

If you post more details about the code or the errors that you are getting, we can provide better answers.

于 2013-02-26T21:11:34.707 に答える
0

静的レベルのロックは、オブジェクト レベルのロックよりも異なるスレッド間で共有される可能性が高くなります (実際のコードと関連するスレッドに依存するため、非常に一般的な方法で)。

実際には、静的ロックはクラスに関連付けられます。つまり、単一のロック オブジェクトがすべてのスレッド間で共有されます。通常、同じロックにアクセスする必要があるスレッドが増えると、コードにバグがあると、同時実行の問題 (デッドロックや飢餓など) が発生する可能性が高くなります。

一般論として、オブジェクト レベルのロックを使用して同時実行の問題に遭遇した場合、代わりにロックをクラス レベルに昇格させるときにさらに問題が発生する可能性があります。

于 2013-02-26T21:13:28.320 に答える