以primefaces方式执行代码块

你会如何回答以下问题?

java类的方法包含必须以primefaces方式执行的代码块。 使用适当的伪代码解释如何确保以primefaces方式执行此代码块

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

public final AtomicInteger x = new AtomicInteger(0); 

然后确保返回get语句:

 x.get() 

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

 x.getAndIncrement(); 

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

我知道三个有效的atomic定义:

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

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

第二个(ACID中的primefaces)可以近似。 见下文。

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

同步中的primefaces

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

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

ACID中的primefaces

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

这是我接近它的方式:

为了论证,假设你需要对我们称之为exampleObj的对象执行多部分操作,你有三个要执行的操作可以安全地反转,并且所有对example访问都是在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); } } } } 

我相信预期的答案是这样的:

 public class A { public void foo() { // .. some code doSomething(); // the critical part // .. come code } public synchronized void doSomething() { // this is a synchronized method // the critical code } } 

doSomething()的执行并不是真正的primefaces( 免责声明:它与primefaces性非常不同),但synchronized关键字确保只有一个线程可以进入该方法的执行(在A一个实例上)。 我认为这就是他们的意思而不是primefaces性。

这是关于Java中的primefaces性的另一个问题。 你可能会在那里找到有用的东西。