Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and set a global object in Java servlet context

Tags:

I wonder if anyone can advise: I have a scenario where a scheduled job being run by Quartz will update an arraylist of objects every hour.

But I need this arraylist of objects to be visible to all sessions created by Tomcat. So what I'm thinking is that I write this object somewhere every hour from the Quartz job that runs so that each session can access it.

Can anyone say how best this may be achieved? I was wondering about the object being written to servlet context from the Quartz job? The alternative is having each session populate the arraylist of objects from a database table.

Thanks

Mr Morgan.

like image 351
Mr Morgan Avatar asked Jul 09 '10 19:07

Mr Morgan


People also ask

What is get servlet context?

Interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.

Is servlet instance globally scoped?

Yes! Different threads might be used to render request for different users but the same servlet instance is used.So yes the variable will be common to all requests. In-fact this is why it is said we should not have global variables to ensure thread safety . Save this answer.


1 Answers

Yes, I would store the list in the ServletContext as an application-scoped attribute. Pulling the data from a database instead is probably less efficient, since you're only updating the list every hour. Creating a ServletContextListener might be necessary in order to give the Quartz task a reference to the ServletContext object. The ServletContext can only be retrieved from JavaEE-related classes like Servlets and Listeners.

EDIT: In the ServletContextListener, when you create the job, you can pass the list into the job by adding it to a JobDataMap.

public class MyServletContextListener implements ServletContextListener{
  public void contextInitialized(ServletContextEvent event){
    ArrayList list = new ArrayList();

    //add to ServletContext
    event.getServletContext().setAttribute("list", list);

    JobDataMap map = new JobDataMap();
    map.put("list", list);
    JobDetail job = new JobDetail(..., MyJob.class);
    job.setJobDataMap(map);
    //execute job
  }

  public void contextDestroyed(ServletContextEvent event){}
}

//Quartz job
public class MyJob implements Job{
  public void execute(JobExecutionContext context){
    ArrayList list = (ArrayList)context.getMergedJobDataMap().get("list");
    //...
  }
}
like image 72
Michael Avatar answered Sep 27 '22 17:09

Michael