如何最终在try-finally中等待线程完成?

时间:2013-05-06 17:31:47

标签: java jpa jpa-2.0 try-catch-finally try-finally

我在基于Swing的桌面应用程序中使用JPA。这就是我的代码:

public Object methodA() {

  EntityManager em = emf.createEntityManager();
  em.getTransaction().begin();
  boolean hasError = false;

  try {
       SwingUtilities.invokeLater(new Runnable() {
           public void run() {
              // JPA operation does not work here 
              // because transaction has been committed!
           }
       });
       ...
       return xXx;
  } catch (Exception ex) {
       hasError = true;
       em.getTransaction().rollback();
  } finally {
       em.close();
       if (!hasError) {
          em.getTransaction().commit();
       }
  }
  return null;    
}

我正在使用此try - catch - finally来处理需要事务的所有方法。除了具有SwingUtilities.invokeLater()的方法之外,它正在按预期工作。

在新线程中的所有代码执行之前,将会到达

finally;因此,如果SwingUtilities.invokeLater()内有JPA操作,它将失败,因为已经提交了事务。

是否存在try - catch - finally的通用用例,以确保只有在所有代码执行完毕后才会提交事务,包括SwingUtilities.invokeLater()内的代码?

1 个答案:

答案 0 :(得分:1)

你必须重新考虑你的方法。首先,SwingUtilities.invokeLater()不是执行JPA操作的最佳选择。该实用程序方法的主要目的是更新UI。关于你的代码,为JPA操作实现单独的线程,这个线程将采用事务状态的监听器。交易完成后,您将更新UI。

/**
 * Transaction callback.
 */
public interface TransactionListener {
    void onTransactionFinished(boolean hasError);
}

/**
 * Worker Thread which takes data and performs JPA operations.
 */
public class JPATask implements Runnable {
    private final Object dataToPersist;
    private final TransactionListener transactionListener;

    public JPATask(Object dataToPersist,
            TransactionListener transactionListener) {
        this.dataToPersist = dataToPersist;
        this.transactionListener = transactionListener;
    }

    private EntityManager getEntityManager() {/* code is omited */}

    @Override
    public void run() {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            // perform JPA actions here
            em.getTransaction().commit();
            transactionListener.onTransactionFinished(false);
        } catch (Exception ex) {
            em.getTransaction().rollback();
            transactionListener.onTransactionFinished(true);
        }
    }
}

/**
 * Finally you method. Now it looks like this.
 */
public Object methodA() {
    JPATask jpaTask = new JPATask(<data to persist>, new TransactionListener() {
        @Override
        public void onTransactionFinished(boolean hasError) {
            // Update UI. It's time to use SwingUtilities.invokeLater() 
        }
    }).start();     
}