简体   繁体   中英

Long living threads in Java EE

I need to code a Java system with these characteristics.

-When the system starts up, it needs to create some objects that need to live forever while the system is running. Also on the constructor of the objects, new threads will be created and these threads will also need to live while the system is running.

-The system needs to expose a web service that will use the object that were created on startup.

To give a context of what do I need to do, I need to code an app that when it starts up it creates some objects that are in charge of doing a polling task. Also I need a web service that uses these objects to process their requests.

How do I implement these in Java? I was thinking of using Java EE to implement the web services and also because I'm planning to implement a web interface that consumes the web services. But the BIG QUESTION that I have is, how do I implement in Java EE the threads that live forever since the application starts?

If you are not really in the need of an Application server you can provide the webservice also in a J2SE environment . For the threading issues, you might want to have a look at the Executor framework with which you can easily backup your threads by a thread pool and schedule Runnable to do work regurlarly (say every 5 seconds). However, this usually don't mix very good with Java EE containers as spawning threads yourself is discouraged.

You can write a Class which implements Thread, and later create an object from that class with Singleton scope, it will live as long as the system is running. Spring is a great framework to implement this.

http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-factory-scopes-singleton

如果要使用Java EE,则应考虑使用EJB Timer Service

What you can use is Spring Timer task to take care of your polling functionality. Declaring a spring timer task is easy -

<bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
  <!-- wait 10 seconds before starting repeated execution -->
  <property name="delay" value="10000"/>
  <!-- run every 50 seconds -->
  <property name="period" value="50000"/>
  <property name="timerTask" ref="sendEmail"/>
</bean>
<bean id="sendEmail" class="examples.CheckEmailAddress">
  <property name="emailAddresses">
    <list>
      <value>jdoe@test.test</value>
     </list>
  </property>
</bean>

Here any objects that you want to be initialized at startup can be defined as Spring Singleton beans. This should solve your purpose without too much complex coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM