Using threads in web services
Is it possible to use threads in a web service? What I propose is a web service that provides a number of different operations just like a standard web service. However, a new thread would be started at the initialisation point of the web service. This thread would wake up every hour and carry out a small task.
Is this possible?
# 1
I have given this a go. It seems to work in NetBeans5.5 but not in Eclipse WTP. The reason I need to do it in Eclispe WTP is that we need to support Java 1.4.2 whereas I can't seem to create a web service in NetBeans5.5 for 1.4.2, it only lets me create a web service for 1.5.
I have a main class which I use to create a new instance of the thread. In the constructor of this main class I start the thread running. I have an operation called getThreadCount() which returns the current iteration of the loop. However, when I deploy the webservice and call the getThreadCount() operation it seems to kick off a new thread! What's going on here? See code below.
public class AuditMaintenance {
private AuditMaintenanceThread auditMaintenanceThread;
public AuditMaintenance(){
this.init();
}
public void init()
{
auditMaintenanceThread = new AuditMaintenanceThread();
auditMaintenanceThread.start();
}
public void start() {
// TODO implement operation
}
public void stop() {
// TODO implement operation
}
public int getThreadCount() {
// TODO implement operation
return auditMaintenanceThread.getThreadCount();
}
}
public class AuditMaintenanceThread extends Thread{
private int mThreadSleepTime = 1000;
private int mThreadCount = 0;
public AuditMaintenanceThread() {
}
public void run()
{
while(true)
{
System.out.println(mThreadCount + " HELLO WORLD!");
try
{
sleep(mThreadSleepTime);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
mThreadCount++;
}
}
public int getThreadCount()
{
return mThreadCount;
}
}