Inadvertent memory leaks in java:web applications

Source: Internet
Author: User
Tags jboss

Here's an article on how to execute some logic in the Spring MVC Web app as soon as it's started, and today it's not a good way to find out if you're using it, it's easy to leak memory, test code as follows:

1, define a class of apps

Package Com.cnblogs.yjmyzz.web.controller;import Java.util.date;public class App {    Boolean isrun = false;    Public App () {        Isrun = true;    }    public void Start () {        while (isrun) {            System.out.println ("=======> I AM ALIVE = +" + new Date ());            try {                thread.sleep;            } catch (Interruptedexception e) {                e.printstacktrace ();}}    } Public    void Stop () {        isrun = false;    }}

The content in the code is not the focus, just a hint that I intend to instantiate the class when the Spring MVC application starts, executing the Start method, which is to output a sentence every second.

2. Define a listener

Import Com.cnblogs.yjmyzz.web.controller.app;import Org.springframework.context.applicationlistener;import Org.springframework.context.event.contextrefreshedevent;import org.springframework.stereotype.component;@ Componentpublic class Startuplistener implements applicationlistener<contextrefreshedevent> {    app app;    @Override public    void Onapplicationevent (Contextrefreshedevent evt) {        if (Evt.getapplicationcontext (). GetParent () = null) {            new Thread (new Runnable () {                @Override public                void Run () {                    app = new app ();                    App.start ();                }            }). Start ();}}    }

The code is also very simple, the application is started, open a thread, instantiate the app, and then call the App.start () method, run, and as expected, every second output similar to the following content:

=======> I AM ALIVE =>wed Sep 21:55:42 CST 2015

After the formal deployment to JBoss, the problem came, on the JBoss management console, the application to disable even remove, the log still has a similar output above, that is, the app's instance is still alive, its Start method is always running, in other words, The app has not been destroyed.

Simple analysis : After each server of JBoss is started, a JVM instance is started, and a Web application is deployed on that server, and the various resources created within the JVM instance, even if the application is stopped or even deleted, Since there is nothing in the code to clear the app or stop processing the Start method, this instance persists and will not be destroyed unless the server restarts.

Another problem: if the above code, the creation of the part of the thread is removed, changed to direct app = new app (); App.start (); Deployment will find another phenomenon, the log still has the output, that is, the code is executing, but the application in the JBoss state is always isdeploying, the deployment has not ended, always in the state of "deployment."

Cause:the Thread.Sleep () method in the Start method blocks the thread, causing the deployment to fail to complete.

Workaround:

Import Org.springframework.stereotype.component;import Javax.annotation.postconstruct;import Javax.annotation.predestroy;import java.util.Date; @Componentpublic class App {    Boolean isrun = false;    @PostConstruct public    void init () {        System.out.println ("init ==>" + new Date ());        Isrun = true;    }    public void Start () {        while (isrun) {            System.out.println ("=======> I AM ALIVE = +" + new Date ());            try {                thread.sleep;            } catch (Interruptedexception e) {                e.printstacktrace ();}}    } Public    void Stop () {        isrun = false;    }    @PreDestroy public    Void Destroy () {        System.out.println ("Destroy ==>" + new Date ());        Stop ();    }}

Several improvements have been made here:

A) After adding @component, an instance of the app will be created automatically by the spring container, which is managed by the container

b) plus the @predestroy,bean lifecycle is managed by the spring container, the method that adds the annotation to the bean is executed before the bean is destroyed, usually to clean up the resource

c) Move the initialization work to the Init method and tell spring through the @postconstruct annotation that the method is called automatically after the bean's default constructor is called (this step is optional, not required)

@Componentpublic class Startuplistener implements applicationlistener<contextrefreshedevent> {    @Autowired    app app;    @Override public    void Onapplicationevent (Contextrefreshedevent evt) {        if (Evt.getapplicationcontext (). GetParent () = null) {            new Thread (new Runnable () {                @Override public                void Run () {                    app.start ()                }            }). Start ();}}    

Listener in the simple, direct @autowired injection app instance on the line.

Personal advice:

A) If you want to perform certain operations when the Web application is started, especially for long-connected instances of the resource class (for example, loading data into the cache to warm up, connecting to zookeeper monitoring node changes, connecting to FTP for data preparation), preferably to the spring container for automatic creation, And be sure to remember to clean up resources before destroy (ie: disconnect)

b) in the execution logic of the startup, Do not use blocking the operation of the thread (such as Thread.Sleep), otherwise, when the deployment, the actual code has been in the background, the JBoss Management console, has been in the state of deployment, there is no output, let people confused, toss half a day to locate the error, a waste of time, if it is an online production environment, is to Rough things.

Inadvertent memory leaks in java:web applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.