java – 以原子方式执行代码块

你会如何回答以下问题?

A method of a java class contains a block of code that must be
executed atomically. Explain,using appropriate pseudo-code,how you
would ensure that this block of code is executed atomically

我会通过制作方法来实现这一点吗?

public final AtomicInteger x = new AtomicInteger(0);

然后确保返回get语句:

x.get()

如果我想增加x的值,我会这样做吗?

x.getAndIncrement();

解决方法

答案取决于你对“原子”的定义

我知道三个有效的原子定义:

>同步中的原子:一次只能有一个线程执行代码;
> ACID中的原子:所有的动作/阻止都会发生,或者都不会发生;
>不间断的原子:一旦块启动,即使通过任务切换也不会中断.

一个可能是你的教授的意思,而且很容易实现(见下文).

第二个(ACID中的原子)可以近似.见下文.

第三个简单地无法在Java中得到保证 – 它不提供对不间断性所需的“关键部分”原语的访问.幸运的是,对此的需求几乎仅限于操作系统和设备驱动程序.

同步中的原子

这是相对简单的:只需将代码块包含在同步块中即可.我已将它显示为下面的离散块,但还有其他选项:

public void doSomethingQuasiAtomic() {
   synchronized (exampleLock) {
      // Your code block goes here. 
      // Only one thread will ever be in this block at a time.
      ...
   }
}

ACID中的原子

对于ACID原子性没有通用的解决方案,但它也可以使用同步代码进行近似.为了做到这一点,动作的每个部分必须是安全可逆的.

这就是我接近它的方式:

为了便于论证,假设您需要对我们称之为exampleObj的对象执行多部分操作,您可以执行三个可以安全撤消的操作,并且可以在exampleLock上同步对示例的所有访问.

synchronized(exampleLock) {
        boolean actionOneDone=false;
        boolean actionTwodone=false;
        boolean actionThreeDone=false;
        try {
            actionOneDone=doActionOne(exampleObj);    // or perhaps exampleObj.doActionOne();
            actionTwodone=doActionTwo(exampleObj);
            actionThreeDone=doActionThree(exampleObj);
        } catch (Exception ex) {
            // Whatever seems appropriate here.
        } finally { 
            if (! (actionOneDone && actionTwodone && actionThreeDone)) {
                /* At least one part Failed.  Back out the completed actions in reverse order.  
                 * Note that we never need to reverse action three since if it completed,so did the others.
                 */
                if (actionTwodone) {
                   reverseActionTwo(exampleObj);    // or perhaps exampleObj.reverseActionTwo();
                }
                if (actionOneDone) {
                   reverseActionOne(exampleObj);
                }
            }
        }
    }

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...