Iterating over select available threads

M

Mitch

Hi, I have some new experience with threads and collections and servlets
and am now looking at a way of throwing the three together.

I have a program that currently fires off threads at random intervals
and does some stuff, and holds some information individual to each thread.

I also have a servlet which is designed to output the information of
this system in XML format.

I would like to find a way to allow the servlet to iterate over the
running threads and obtain the information it requires.

One idea I had was to add each object that implements the Runnable
interface to an ArrayList - will this affect the Runnable nature of the
object? If I did this I could then iterate over the indexes of the
ArrayList.

Is there a cleaner way of doing this - perhaps an iterator that runs on
threads? (I haven't found any in the Thread class) perhaps adding the
threads to a thread group adds the required functionality?

Thanks for any ideas,

Mitch.
 
R

Robert Klemme

Mitch said:
Hi, I have some new experience with threads and collections and
servlets and am now looking at a way of throwing the three together.

I have a program that currently fires off threads at random intervals
and does some stuff, and holds some information individual to each
thread.
I also have a servlet which is designed to output the information of
this system in XML format.

I would like to find a way to allow the servlet to iterate over the
running threads and obtain the information it requires.

One idea I had was to add each object that implements the Runnable
interface to an ArrayList - will this affect the Runnable nature of
the object?

Not at all. The only impact will be GC if you forget to remove them after
they did their job.
If I did this I could then iterate over the indexes of
the ArrayList.

Personally I'd prefer the default iteration. But keep in mind that your
collection may change while you're iterating it. A good solution is to
create a copy or transform it into an array before starting the iteration.
Is there a cleaner way of doing this - perhaps an iterator that runs
on threads? (I haven't found any in the Thread class) perhaps adding
the threads to a thread group adds the required functionality?

It's a bit difficult with more precise information about what your code
actually does. The approach to put Runnables into a container (ArrayList or
whatever) does certainly work. You just have to make sure terminated
Runnables are removed. A ThreadGroup may make things easier (haven't worked
much with them). You will have to take care of proper synchronization - but
this you will have to do regardless which approach you use.

Kind regards

robert
 
M

Mitch

It's a bit difficult with more precise information about what your code
actually does. The approach to put Runnables into a container
(ArrayList or whatever) does certainly work. You just have to make sure
terminated Runnables are removed. A ThreadGroup may make things easier
(haven't worked much with them). You will have to take care of proper
synchronization - but this you will have to do regardless which approach
you use.

Kind regards

robert

Below is a cut down (but not by much) copy of what I am doing.

It sets up a new train both northbound and southbound on their
respective lines.

///////////////////////////////////////////////
////
while(true)
{

//Add more passengers
/////////////////////


threadIter++;

trainID = "Train" + threadIter ;
ThreadGenerator = new Random(threadIter);



//<editor-fold defaultstate="collapsed" desc="Passenger setup">

//</editor-fold>


// Here it sleeps and sends a train off in each
direction //every 20 minutes
try{ Thread.sleep( 20*60*1000 ); }
catch(InterruptedException e) { System.out.println("WTF");}

randomTrainN = new Train(ThreadGenerator.nextInt(100), 4,
REDDITCHtoLICHFIELD_TRENT_VALLEY, trainID + " Northbound");

randomTrainS = new Train(ThreadGenerator.nextInt(100), 4,
LICHFIELD_TRENT_VALLEYtoREDDITCH, trainID + " Southbound");

randomTrainNThread = new Thread(randomTrainN);
randomTrainSThread = new Thread(randomTrainS);

randomTrainNThread.start();
randomTrainSThread.start();


}//end while(true)

//////////////////////////////////////////////////////////////////////////

Now each train has a geographical location relative to its position on
the route (E.G. LICHFIELD_TRENT_VALLEYtoREDDITCH which is an ArrayList
of RailSections including stations, Signals etc.)

My plan is initially to iterate over all the trains (which are Runnable)
and retrieve their current location and output it using a servlet.

Adding the trains to an ArrayList is pretty easy, just .add them to one
prior to running them. However how would I go about removing the dead
ones? Perhaps some try clause, and then a catch for
nullpointerexception then iterate and remove all that == null? in the
catch clause. I will try that in the meantime but would gladly take in
any further advice (as that seems clumsy) :)
 
M

Mitch

Short Version:

Once I call init from a servlet it freezes and will no longer process
requests from the server, does anyone know why this may be?

Longer Version:

I can't seem to get over a specific problem.

If i call init from one servlet to intiate my system then the servlet
kind of freezes and doesn't print any of the stuff its supposed to (It
seems to get caught up in the init method and never returns) and as
such I can't do anything with it. I can't then access the information
from another servlet as I don't have access to the objects instantiated
in the original servlet.

The servlets out.print fine if the init method is commented out (Though
obviously nothing useful)...

Can anyone think of a way around this? It has had me stumped for hours
now.

Code examples:

Servlet one:

/*
* XMLTest.java
*
* Created on 11 March 2006, 17:52
*/

package fyp_rail_simulation;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
*
* @author Mitch
* @version
*/
public class XMLTest extends HttpServlet {

/** Processes requests for both HTTP <code>GET</code> and
<code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
out = response.getWriter();


/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet XMLTest</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet XMLTest at " + request.getContextPath
() + "</h1>");
out.println("</body>");
out.println("</html>");
*/
out.close();
}




// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>


////////
/// Here is the init code
////////
public void init(ServletConfig config)
throws ServletException
{
super.init(config);

RSS = new RailSimulationSystem();

RSS.run();

}
private PrintWriter out;
private RailSimulationSystem RSS;
private ArrayList<Train> servletCopyRUNNING_TRAINS;
private int i;
}

As you can see there is hardly anything to the init code, however it
gets this far (I do know it gets this far as my sytem is initiated and
I get all the appropriate println's in my debug window) however the
servlet will never process any of the servlet code in the
processRequest method. I can't access the RSS object from any other
servlet so does anyone have an idea of what might be going on that I'm
missing?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top