您的位置:首页 > 产品设计 > UI/UE

AbstractQueuedSynchronizer 源码理解

2015-09-28 23:35 405 查看
UnSafe类(原子操作):
/**
* 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。
*
* @param obj 需要更新的对象
* @param offset obj中整型field的偏移量
* @param expect 希望field中存在的值
* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值
* @return 如果field的值被更改返回true
*/
public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);
AbstractQueuedSynchronizer类:
*
<p>To enqueue into a CLH lock, you atomically splice
it in as new
[align=left] * tail. To dequeue, you just set the head field.[/align]
*
<pre>
* +
------+ prev +-----
+ +-----+
[align=left] * head | | <---- | | <---- | | tail[/align]
* +
------+ +-----
+ +-----+
*
</pre>

[align=left] /**[/align]
[align=left] * Inserts node into queue, initializing if necessary. See picture above.[/align]
*
@param
node the node to insert
*
@return
node's predecessor
[align=left] */[/align]

private
Node enq(
final
Node node) {

for
(;;) {
Node t =
tail;

if
(t ==
null
) {
// Must initialize
//如果头部为空,则更新,并赋值给tail

if
(compareAndSetHead(new
Node()))

tail
=
head;
}
else
{

//让tail指向新插入的结点
node.
prev
= t;

if
(compareAndSetTail(t, node)) {
t.
next
= node;

return
t;
[align=left] }[/align]
[align=left] }[/align]
[align=left] }[/align]
[align=left] }[/align]

[align=left] /**[/align]
[align=left] * Creates and enqueues node for current thread and given mode.[/align]

[align=left] *[/align]
*
@param
mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared 标明是否共享: addWaiter(Node.
EXCLUSIVE) null
addWaiter(Node.
SHARED); new Node();

*
@return
the new node
[align=left] */[/align]

private
Node
addWaiter(Node mode) {
Node node =
new
Node(Thread.currentThread(), mode);

// Try the fast path of enq; backup to full enq on failure
Node pred =
tail;

if
(pred !=
null) {
node.
prev
= pred;

if
(compareAndSetTail(pred, node)) {
pred.
next
= node;

return
node;
[align=left] }[/align]
[align=left] }[/align]
[align=left] enq(node);[/align]

return
node;

[align=left] }[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: