Suppose I am using Apache Tomcat, and as Tomcat starts up for the first time I instantiate a java class that I will pass as a shared object for all messages that arrive. As new HTTP Requests arrive, request processing methods are passed this shared object along with the HTTP Request object, and the required work is done.
This set up works well, but I would like to change it, and I would like your advice and opinion on the wisdom of doing so.
First: the shared object (I'll call it objectX) has an array of names that are allocated for on startup (String[ ] names = new String[nnames]). If new names are to be added to the array and objectX, then Tomcat must be brought down, and when it is restarted, the existing names and all new names are read and put in the array of names to be shared.
I would like to make adding names dynamic, so that I can receive a message (an HTTP Request) that says "addThisName", and it adds it to objectX. I do not believe the existing array can be added to, since the size of the array was allocated at startup. However, it seems to me that instead of an pre-allocated array of names, I could use a Vector to hold the names instead, and new names could be added to the Vector in real time, such that all subsequent users would see the new name.
Would it be dangerous to use a Vector on such a shared object that is used during all message processing? Any tips or warnings will be greatly appreciated.
It depends on exactly how you are using it. If an object is read only, it is fine. If it is mostly read only with a few additions to the end and you don't care exactly (to the second) when the new additions are picked up, that is fine too. This sounds to me like your scenario.
Thanks for the reply. This shared object is read only, but with the caveat that when a message arrives that says "addThisName" to the Vector (using the addElement() method), I want to add the name and, of course, have it available to all subsequent users as soon as possible.
It seems to me that if I use a Vector to store this list of names (instead of an array), then adding a name to the Vector using the addElement() method would make the change available almost immediately for all new messages. Right? Isn't the name added to some "shared memory" in the instance of the shared object? My fear: adding to the shared object causes some memory corruption or some kind of exception.
Vector is synchronized, and there is a risk of a ConcurrentModificationException if one thread is iterating over the Vector while another thread is modifying it. Your code will need to be able to accommodate this situation.
Another option is to employ a CopyOnWriteArrayList. I've used it under heavily load in my applications without ever receiving the death exception: ConcurrentModificationException - One advantage is you don't have to lock it during interation. Your options are endless...