Reputation: 707
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?
Upvotes: 1
Views: 979
Reputation: 13799
If you are going the Java EE way, you should consider the EJB Timer Service.
Upvotes: 2
Reputation: 7388
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.
Upvotes: 1
Reputation: 7590
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>[email protected]</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.
Upvotes: 2
Reputation:
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
Upvotes: 2