4

オブジェクトがロックのために null ではないことを検出するたびに、ブロックを同期することは可能ですか? 同期するためのある種の最善の試みです。私はこの方法でコードを書くことができますが、少し冗長に思えます:

if ( lock_object != null )
{
    synchronized(lock_object) {
        doSomething();
    }
}
else
{
    doSomething();
}

このコードを構造化するより良い方法はありますか?

4

2 に答える 2

1

It is possible, but has no sense. The method doSomething reads/writes some data, say, fields of the object the method belongs to. The most evident and reliable way is to declare the method doSomething synchronized, as well as all other methods which can be called from different threads. Synchronized block is used only for optimizations, and novice programmers should avoid using it.

As for the "best effort", best effort in programming means no less than reliable and proven functionality. All other "efforts" are not best, including your code.

于 2013-07-29T05:29:34.870 に答える