crypto9294
crypto9294

Reputation: 171

Static variable not getting update in Apache tomcat servlet instantiation

I am a tomcat/servlet newbie and have been stuck on this for the last 3/4 days. Any help is appreciated! I have a servlet class that has a static variable name_print. The static function appInput takes in a string and sets name_print to that string. The code for this class, appmonitor.java, is below:

package AppMonitor_pack;

import statments...

private static String name_print;
public app_monitor() {
    // TODO Auto-generated constructor stub
}

/**
 * @param args
 */
public static void main(String[] args) {
    // TOsDO Auto-generated method stub

}

public static void appInput (String name){
    name_print = name;
    System.out.println("From appInput " + name_print);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();
    writer.println("<body> "+ name_print +" </body>");
}

}

I have included this simple project in another project called Sockets. In that, I have a Listening socket that recieves a string called name. I call the static function appInput of the first project and pass in the recieved string name to it, so that it sets name_print to this new value.

The relevant line in Socket.java for this is: app_monitor.appInput(name);

WHen I compile and run this, I see that the value name is set to some input value "abc". Then the debugger goes into the appInput function of the other project, and sets the value of name_print to "abc" too.

But when I refresh the webpage where the tomcat server is running, it never shows the newly set value of name_print, but continues to show the old value "null" that was set when the appMonitor servlet class loads for the first time.

I have tried to figure out the problem to no avail for 4 days. Any ideas/help? Thanks!

Upvotes: 0

Views: 1314

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500665

WHen I compile and run this, I see that the value name is set to some input value "abc". Then the debugger goes into the appInput function of the other project, and sets the value of name_print to "abc" too.

It sounds like you're running this separately from Tomcat. That means you've not just got two different classloaders - you've got two entirely separate JVMs which just happen to run on the same computer. The static variable isn't going to be shared between those processes.

It's not really clear what you're trying to achieve, but if you want information from one process to be available in a separate process, you'll need to use some cross-process communication, or share something more global than just a static variable - e.g. writing the data to a file within one process, then reading it from a file in the other process.

Upvotes: 1

Related Questions