27

トランザクション管理にSpringを使用するJavaアプリケーションでスレッド化を実装する方法を理解しようとしています。SpringのドキュメントでTaskExecutorセクションを見つけましたが、ThreadPoolTask​​Executorは私のニーズに合うように見えます。

ThreadPoolTask​​Executor

この実装は、Java 5環境でのみ使用できますが、その環境で最も一般的に使用される実装でもあります。java.util.concurrent.ThreadPoolExecutorを構成するためのBeanプロパティを公開し、それをTaskExecutorでラップします。ScheduledThreadPoolExecutorなどの高度なものが必要な場合は、代わりにConcurrentTaskExecutorを使用することをお勧めします。

しかし、どうやって使うのかわかりません。私はしばらくの間良い例を探していましたが、運がありませんでした。誰かが私を助けることができれば私はそれをいただければ幸いです。

4

1 に答える 1

36

とてもシンプルです。アイデアは、Bean である executor オブジェクトがあり、新しいタスクを (新しいスレッドで) 起動したいオブジェクトに渡されるということです。良い点は、Spring 構成を変更するだけで、使用するタスク エグゼキューターのタイプを変更できることです。以下の例では、いくつかのサンプル クラス (ClassWithMethodToFire) を取り上げ、それを Runnable オブジェクトにラップして発火を行います。また、Runnable を独自のクラスに実際に実装し、execute メソッドで を呼び出すこともできますclassWithMethodToFire.run()

これは非常に簡単な例です。

public class SomethingThatShouldHappenInAThread {
     private TaskExecutor taskExecutor;
     private ClassWithMethodToFire classWithMethodToFire;

     public SomethingThatShouldHappenInAThread(TaskExecutor taskExecutor,
                                               ClassWithMethodToFire classWithMethodToFire) {
          this.taskExecutor = taskExecutor;
          this.classWithMethodToFire = classWithMethodToFire;
     }

     public void fire(final SomeParameterClass parameter) {
          taskExecutor.execute( new Runnable() {
               public void run() {
                    classWithMethodToFire.doSomething( parameter );
               }
          });
     }
}

そして、ここにSpring Beanがあります:

<bean name="somethingThatShouldHappenInAThread" class="package.name.SomethingThatShouldHappenInAThread">
     <constructor-arg type="org.springframework.core.task.TaskExecutor" ref="taskExecutor" />
     <constructor-arg type="package.name.ClassWithMethodToFire" ref="classWithMethodToFireBean"/>
</bean>

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
     <property name="corePoolSize" value="5" />
     <property name="maxPoolSize" value="10" />
     <property name="queueCapacity" value="25" />
</bean>
于 2009-05-12T14:13:25.680 に答える