本文介绍了Java内存模型:重新排序和并发锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java meomry模型要求在同一监视器上同步的 synchronize 块对这些块中修改的变量强制执行之前的实现。示例:

The java meomry model mandates that synchronize blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those blocks. Example:

// in thread A
synchronized( lock )
{
  x = true;
}

// in thread B
synchronized( lock )
{
  System.out.println( x );
}

在这种情况下,保证线程B会看到 x == true 只要线程A已经传递了 synchronized -block。现在我正在重写大量代码,以便在 java.util.concurrent 中使用更灵活(并且说更快)的锁,特别是的ReentrantReadWriteLock 。所以示例如下所示:

In this case it is garanteed that thread B will see x==true as long as thread A already passed that synchronized-block. Now I am in the process to rewrite lots of code to use the more flexible (and said to be faster) locks in java.util.concurrent, especially the ReentrantReadWriteLock. So the example looks like this:

EDIT :示例被破坏,因为我错误地转换了代码,如 matt所示b'/ em>的。修正如下:

EDIT: The example was broken, because I incorrectly transformed the code, as noted by matt b. Fixed as follows:

// in thread A
lock.writeLock().lock();
{
  x = true;
}
lock.writeLock().unlock();

// in thread B
lock.readLock().lock();
{
  System.out.println( x );
}
lock.readLock().unlock();

但是,我没有看到内存模型规范中的任何提示,这些锁也意味着需要订购。查看实现,它似乎依赖于访问 AbstractQueuedSynchronizer 中的volatile变量(至少对于sun实现)。然而,这不是任何规范的一部分,而且这些变量给出的内存障碍并没有真正考虑到对非易失性变量的访问,是吗?

However, I have not seen any hints within the memory model specification that such locks also imply the nessessary ordering. Looking into the implementation it seems to rely on the access to volatile variables inside AbstractQueuedSynchronizer (for the sun implementation at least). However this is not part of any specification and moreover access to non-volatile variables is not really condsidered covered by the memory barrier given by these variables, is it?

所以,以下是我的问题:

So, here are my questions:


  • 假设与旧同步的订单相同,是否安全? code> blocks?

  • 这是否记录在某处?

  • 访问任何volatile变量是否为任何其他变量的内存屏障?

问候,
Steffen

Regards, Steffen

-

对Yanamon的评论:

Comment to Yanamon:

请看以下代码:

// in thread a
x = 1;
synchronized ( a ) { y = 2; }
z = 3;

// in thread b
System.out.println( x );
synchronized ( a ) { System.out.println( y ); }
System.out.println( z );

从我的理解,内存屏障强制第二个输出显示2,但没有保证的影响关于其他变量......?那么如何将其与访问volatile变量进行比较?

From what I understood, the memory barrier enforces the second output to show 2, but has no guaranteed affect on the other variables...? So how can this be compared to accessing a volatile variable?

推荐答案

来自:

* A successful lock operation has the same memory synchronization effects as a successful Lock action.
* A successful unlock operation has the same memory synchronization effects as a successful Unlock action.

锁定和解锁
操作失败,以及可重入
锁定/解锁操作,不要
需要任何内存同步
效果。

Unsuccessful locking and unlocking operations, and reentrant locking/unlocking operations, do not require any memory synchronization effects.

这篇关于Java内存模型:重新排序和并发锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:24