【问题标题】:Does a call to a DB spawn a new thread in a method对数据库的调用是否会在方法中产生新线程
【发布时间】:2018-06-14 18:26:21
【问题描述】:

在下面的 Product 类中,我有一个方法调用 addDetails

 class Product{
    addDetails(){
       productDAO.save(productDetails) //Line 3
       addAdditionalDetails(productDetails) //Line 4
    }
   }

    class ProductDAO {
       @Transactional
       public void save(Product productDetails){
           entitiyManager.merge(productDetails)
       }
    }

在产品类中,当 control(thread) 到达第 3 行时,会生成一个新线程,第 4 行与第 3 行的保存同时执行。或者线程首先执行第 3 行,当它完全执行第 3 行时转到第 4 行?

【问题讨论】:

    标签: java spring multithreading hibernate


    【解决方案1】:

    只有在第 3 行被返回时,第 4 行才会被执行。

    确实,您不会在新线程中执行ProductDAO.save()。此外EntitiyManager.merge也不会在自己的线程中执行。
    因此,对ProductDAO.save() 的调用将仅在返回entitiyManager.merge(productDetails) 时返回。

    如果您编写如下代码,情况会有所不同,第 3 行和第 4 行的顺序将无法预测:

    class ProductDAO {
        @Transactional
         public void save(Product productDetails){
           new Thread( ()-> entitiyManager.merge(productDetails)).start();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-14
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2011-09-16
      • 2019-10-12
      相关资源
      最近更新 更多