Spring 对象池 &线程阻塞

发布于 2024-10-01 15:20:04 字数 727 浏览 5 评论 0原文

我有一个为 bean 定义的 Spring CommonsPoolTargetSource 。我试图了解池的工作原理,以及对象何时返回池。

具体来说,如果我有一个工作线程,它接受一个池化对象并调用它的两个方法,如下所示:

public class MyWorker {
    @Resource
    Foo pooledFoo;

    void doWork()
    {
        pooledFoo.doStepA();
        pooledFoo.doStepB();
    }
}

从我运行的测试中可以看到,pooledFoo实际上并不是Foo,而是Pool提供的一个代理。上面的流程是:

  • foo 上调用 doStepA() 从池中检索一个值(如果没有可用的值,则阻塞线程),
  • pooledFoo 上执行 doStepA
  • 当 doStepA 完成时,在 ,pooledFoo 实例返回到池
  • 控制返回到 doWork 方法,并且该方法继续

如果这是正确的(请告诉我如果不是),是否可以假设调用 doStepB() 时从池中返回的 pooledFoo 是否与为 doStepA() 返回的实例不同?

I have a Spring CommonsPoolTargetSource defined for a bean. I'm trying to understand how pooling works, and when an object is returned the the pool.

Specifically, if I have a worker, which takes a pooled object and invokes two methods on it, as follows:

public class MyWorker {
    @Resource
    Foo pooledFoo;

    void doWork()
    {
        pooledFoo.doStepA();
        pooledFoo.doStepB();
    }
}

From what I can see in the tests I've run, pooledFoo is not actually an instance of Foo, but a proxy provided by the Pool. The flow in the above would be:

  • Invoking doStepA() on foo retrieves a value from the pool (blocking the thread if one is not available),
  • doStepA is executed on the pooledFoo
  • when doStepA completed, pooledFoo instance is returned to the pool
  • control returns to the doWork method, and the method continues

If this is correct (please tell me if it's not), is it fair to assume that the pooledFoo returned from the pool when doStepB() is invoked, will not be the same instance that was returned for doStepA()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烈酒灼喉 2024-10-08 15:20:04

您对流程的描述是正确的 - 该对象将在每次调用之前从池中借用,然后返回给它。

但是,您的下一个假设是错误的 - 完全有可能针对与 stepA 相同的池实例调用 stepB。这取决于池上的“搅动”——不同线程借用和返回对象的频率。在低负载下,同一个对象可能会被重复使用。

所以这里没有任何保证。对于池化对象,您通常希望让池化对象处于适合下一个借用者使用的状态,无论借用者是否是同一线程。

Your description of the flow is correct - the object will be borrowed from the pool before each invocation, and returned to it afterwards.

However, you next assumption is wrong - it's entirely possible that stepB will be invoked against the same pooled instance as stepA. It depends on the "churn" on the pool - how often are objects borrowed and returned by different threads. Under low load, the same object might be reused.

So there's no guarantee of anything here. With pooled objects, you generally want to leave the pooled object in a state where it is fit to be used by the next borrower, regardless of whether not the borrower is the same thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文