q********y 发帖数: 162 | 1 public class Foo
{
private const int SyncLock = 1 << 10;
public void Execute()
{
lock((object)SyncLock)
{
//complex logic
}
}
} | k**********g 发帖数: 989 | 2
SyncLock is a primitive value. Strictly speaking, it is not even a value,
because it is a compile time constant. If you load this value into a CPU
register, the generated code will just write the constant 1024. No memory
loads.
When you do a ((object)SyncLock), this is called boxing. Boxing creates a
new object on the heap, with enough space for storing a copy of the value.
so, it is roughly similar to this in C++ :
struct BoxedInteger { int value; }
BoxedInteger* pObject = new BoxedInteger;
pObject->value = 1024;
Every time the code is entered, it will create a new boxed object. Thus,
each call locks a different object. There is no synchronization, and
therefore multiple threads will enter the complex logic at the same time.
【在 q********y 的大作中提到】 : public class Foo : { : private const int SyncLock = 1 << 10; : public void Execute() : { : lock((object)SyncLock) : { : //complex logic : } : }
| f*******t 发帖数: 7549 | 3 这种错误在java里比较常见
★ 发自iPhone App: ChineseWeb 7.8
【在 k**********g 的大作中提到】 : : SyncLock is a primitive value. Strictly speaking, it is not even a value, : because it is a compile time constant. If you load this value into a CPU : register, the generated code will just write the constant 1024. No memory : loads. : When you do a ((object)SyncLock), this is called boxing. Boxing creates a : new object on the heap, with enough space for storing a copy of the value. : so, it is roughly similar to this in C++ : : struct BoxedInteger { int value; } : BoxedInteger* pObject = new BoxedInteger;
| q********y 发帖数: 162 | 4 Thanks!
【在 k**********g 的大作中提到】 : : SyncLock is a primitive value. Strictly speaking, it is not even a value, : because it is a compile time constant. If you load this value into a CPU : register, the generated code will just write the constant 1024. No memory : loads. : When you do a ((object)SyncLock), this is called boxing. Boxing creates a : new object on the heap, with enough space for storing a copy of the value. : so, it is roughly similar to this in C++ : : struct BoxedInteger { int value; } : BoxedInteger* pObject = new BoxedInteger;
| m*******l 发帖数: 12782 | 5 C# 和 Java 的boxing, unboxing确实和C++相比比较烦
【在 f*******t 的大作中提到】 : 这种错误在java里比较常见 : : ★ 发自iPhone App: ChineseWeb 7.8
| g*****g 发帖数: 34805 | 6 Java has an object pool between -128 and 127 and it's actually OK to lock in
this range. But it's been well know not to lock on any primitive.
【在 f*******t 的大作中提到】 : 这种错误在java里比较常见 : : ★ 发自iPhone App: ChineseWeb 7.8
|
|