Managing memory between screens?

I have a few screens. A login, a home page, and a data page. The data page has a grid that pulls data from an Access database, and displays it in a grid.

From running it on Eclipse my computer, I notice that it jumps from 300mb of ram to 800mb of ram, and it never goes back down (while the server is up). Even if I close out of the browser. Sometimes if I do multiple runs, it’ll go from 1.1gb back to 800gb, but never back to 300mb… but sometimes it won’t go back down at all, and just continues increasing.

I read that it might be better to use a Navigator
over here

Navigator navigator = new Navigator(); navigator.addView(HomeScreen.VIEW_NAME, HomeScreen.class); navigator.addView(DataView.VIEW_NAME, DataView.class); } than to use

UI.getCurrent().setContent(new DataScreen()); Is this true?

Or maybe I have a memory leak in my data page? It’s a big page. I’m not sure if Lazy loading will help?

This uses a lot of other libraries (HTTPUnit, UCanAccess, and HTTPClient)

[code]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.vaadin.annotations.Theme;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Grid.MultiSelectionModel;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;

@Theme(“demotimeentrygrid”)
public class DataScreen extends GridLayout{
//Makes Class serializable
private static final long serialVersionUID = 1L;
//Container/Arraylist like object to hold all pulled data from Access db.
BeanContainer<String, Bean> beanList = new BeanContainer<String, Bean>(Bean.class);
//Where the Access db is located.
private String logName = “\\server\folder\logging\TextFileslog.txt”;

public DataScreen(){
    //Set Website URI fragment (url)
    UI.getCurrent().getPage().setUriFragment("Data");

    //Size of rows/columns for layout.
    setRows(4);
    setColumns(3);
    
    //Sets Unique Index for the Grid (similar to a index for a table)
    beanList.setBeanIdProperty("RID");
    
    //Creates a Header at the Top of the page, and spaces it.
    Label titleLabel = new Label("Data Entry<br></br>");
    titleLabel.setStyleName("TitleLabel");
    titleLabel.setContentMode(ContentMode.HTML);
    titleLabel.setWidth("100%");
    
    //setup DateField, user can filter entries by date.
    DateField df = new DateField();
    df.setValue(new Date());
    Button dateButton = new Button("Go");
    
    //Sets up the grid of beans.
    Grid grid = new Grid (beanList);
    
    grid.removeColumn("RID"); //Don't show this column, but it is there.
    grid.setSelectionMode(SelectionMode.MULTI); //Allows to pick multiple entries.
           
    ////////////Button Functions

    //When user picks a date and presses Go, this button loads
    //The beans straight from the acess db. Right now, it's connected to a test db.
    dateButton.addClickListener(new ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void buttonClick(ClickEvent event){
            dateButton.setEnabled(false);
            //Resets beanList if it was previously populated
            beanList.removeAllItems();
            grid.setSelectionMode(SelectionMode.NONE);
            grid.setSelectionMode(SelectionMode.MULTI);

            try {
                
                Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
                
                Connection conn=DriverManager.getConnection("jdbc:ucanaccess://\\\\server\\folder\\MainLog.mdb;SingleConnection=true");
                 
                Statement s = conn.createStatement();
                Bean bean = new Bean();

                 ResultSet rs = s.executeQuery("SELECT [Department]

, [UName]
, [Entry-Date]
from [DataTable]
where [Entry-Date]
= #“+new SimpleDateFormat(“MM/dd/yyyy”).format(df.getValue())+”#");

                 while (rs.next()) {
                     bean.setDept(rs.getString(1));
                     bean.setUName(rs.getString(2));
                     bean.setEntryDate(rs.getString(3).split("\\s")[0]

.split(“-”)[1]

  • rs.getString(3).split(“\s”)[0]
    .split(“-”)[2]

  • rs.getString(3).split(“\s”)[0]
    .split(“-”)[0]
    .substring(2));
    beanList.addBean(bean);
    bean = new Bean();
    } //End While
    s.close();
    rs.close(); //Close recordset
    conn.close(); //Close Access connection
    } catch (ClassNotFoundException | SQLException e) {
    e.printStackTrace();
    }
    dateButton.setEnabled(true);
    } //End Click Listener
    }); //End Click Event

      //Sends the Selected Time Entries to Online db
      Button btnSendOnlineDb = new Button("Send Selected to DB");
      btnSendOnlineDb.setStyleName("submitButton");
      
     btnSendOnlineDb.addClickListener(new ClickListener() {
          private static final long serialVersionUID = 1L;
    
          @Override
          public void buttonClick(ClickEvent event){
              btnSendOnlineDb.setEnabled(false);
              
              //Sets up WebClient to go to online db.
              WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED);
              //Turns off useless logger that comes with UCanAccess
              java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
              
              try{
              //Container to hold failed posted TimeEntries.
                  BeanContainer<String, Bean> failures = new BeanContainer<String, Bean>(Bean.class);
                  failures.setBeanIdProperty("RID");
                  File log = new File(logName);
                  PrintWriter pw = new PrintWriter(new FileWriter(log,true));
                  
                 
                  String sCurrentLine;
               
               
                  //Navigate to Online page page, and log in.
                  HtmlPage page = (HtmlPage) webClient.getPage(onlineDbPage);
                  HtmlForm form = page.getFormByName("loginfm");
                  form.getInputByName("user").setValueAttribute(UserName);
                  HtmlInput passWordInput = form.getInputByName("password");
                  passWordInput.removeAttribute("disabled");
                  passWordInput.setValueAttribute(Pword);
                  page = form.getInputByValue("Login").click();
                  webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    
                  //Gets which Time entries were selected by User.
                  MultiSelectionModel selection = (MultiSelectionModel) grid.getSelectionModel();
                  selection.getSelectedRows();
                  
                  //Cycles through each one and submits them to online db
                  for (Object itemId: selection.getSelectedRows()){
                      
                      //Try/Catch for following errors:
                          //Work Order Not Found
                          //Work Order Closed
                      
                      try {
                          beanList.getItem(itemId).getBean();
                          
                          if (beanList.getItem(itemId).getBean().getWo().contains("-")){
                              beanList.getItem(itemId).getBean().setWo(beanList.getItem(itemId).getBean().getWo().split("-")[0]
    

.toUpperCase());
}

                        HtmlPage mainPage = webClient.getPage("websiteEntry");
                        form = mainPage.getFormByName("timeForm");
                        form.getInputByName("chkaction").setValueAttribute("checked");
                        form.getInputByName("E2EMPL").setValueAttribute(beanList.getItem(itemId).getBean().getDept());
                        form.getInputByName("ww_fE2WKDT").setValueAttribute(beanList.getItem(itemId).getBean().getEntryDate());

                        mainPage = form.getButtonByName("timeButton").click();
                        //usually when an entry fails, the follow page has the words "row 1" in it. This
                        //Catches it and stores it to show the user at the end. It also logs it in a text file.

                        //Catches basic errors and logs them
                            //Wrong syntax in fields, etc
                        if (mainPage.asText().contains("row 1")){
                            failures.addBean(beanList.getItem(itemId).getBean());
                        }
                        System.out.println(mainPage.asText());                
                    }catch (Exception e){
                        e.printStackTrace();    
                        
                        // Catches the major errors and logs them.
                        failures.addBean(beanList.getItem(itemId).getBean());
                        continue;
                    }
                    
                }//End For Loop
                h = null;
                if (failureEntries.size() >0)
                    UI.getCurrent().addWindow(new BeanErrorWindow(failures));
               
                webClient.close();
                
            
            }catch(FailingHttpStatusCodeException | ElementNotFoundException | IOException e){
                e.printStackTrace();
            }                
            Notification.show("Completed.");
            btnSendOnlineDb.setEnabled(true);
        } // Click Event
        
        
    }); //Online db Button ClickListener

    ////////////End Button Functions

    
    //Sets up JavaScript
    
    
    
    
    ////////Sets up look of page.
    
    //Get Width and Height of Browser Window.
    int browserWidth =  UI.getCurrent().getPage().getBrowserWindowWidth();
    int browserHeight = UI.getCurrent().getPage().getBrowserWindowHeight();

    
    //Sidebar menu.
    MenuLayout menu = new MenuLayout();
    menu.setHeight("100%");
    menu.setWidth(Math.round(.15*browserWidth) + "px");
    
    setHeight(browserHeight+"px");
    addStyleName("backgroundColor");
    addComponent(menu,0,0,0,3);
    addComponent(titleLabel,1,0,2,0);
    addComponent(df,1,1);
    addComponent(dateButton,2,1);
    
    //Grid with the Time Entries
    grid.setWidth(Math.round(.85*browserWidth) + "px");
    grid.setHeight(Math.round(.70*browserHeight) + "px");
    setComponentAlignment(df, Alignment.MIDDLE_RIGHT);
    setComponentAlignment(dateButton, Alignment.MIDDLE_LEFT);
    
    addComponent(btnSendOnlineDb,1,3,2,3);
    setComponentAlignment(btnSendOnlineDb, Alignment.MIDDLE_RIGHT);
    addComponent(grid,1,2,2,2);
    setComponentAlignment(grid, Alignment.MIDDLE_CENTER);
    
}

}
[/code]Is there a way to make sure that this page gets picked up by garbage collector when the user leaves the page? During runtime in Eclipse, if I try to filter by date more than 2-3 times, I almost always get Memory Overhead heap etc error.

After looking through the form, it looks like the problem is BeanItemContainer / BeanContainer.

So I’m trying to use ListContainer but I’m having some trouble since it’s kind of hard to find examples of people using ListContainer.

So far:

ListContainer<Bean> te = new ListContainer<Bean>(Bean.class); gives me:

Jun 16, 2016 9:44:22 AM com.vaadin.server.DefaultErrorHandler doDefault SEVERE: java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap at org.vaadin.viritin.ListContainer.<init>(ListContainer.java:76) at com.example.gridbutton.GridbuttonUI.init(GridbuttonUI.java:43) at com.vaadin.ui.UI.doInit(UI.java:682) at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:214) at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74) at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41) at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1409) at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:364) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.FastHashMap at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167) ... 30 more And I’m not sure why. I have downloaded the apache commons beanutils and commons collections4.


Edit
well ok googling some more, it appears that I need to use Commons Collections 3. So i replaced that and it worked. But to be honest, the BeanItemContainer and ListContainer didn’t have any difference in memory consumption or performance.

I tried with Grid (works fine, but ListContainer had no improvements), then I tried both with MGrid (which actually gave me memory overhead problems) then I tried with MTable, which I don’t really want to use because I need Multiselect and Multiselect is depreciated or doesn’t work in MTable.

Grid Code:

ListContainer<Bean> te = new ListContainer<Bean>(Bean.class); Grid grid = new Grid(te); MGrid Code:

ListContainer<Bean> te = new ListContainer<Bean>(Bean.class); MGrid mgrid = new MGrid(te); I also get this error in MTable so I really don’t want to use MTable:

Jun 16, 2016 10:31:44 AM com.vaadin.server.DefaultErrorHandler doDefault

SEVERE:
com.vaadin.ui.Table$CacheUpdateException: Error during Table cache update.
    at com.vaadin.ui.Table.maybeThrowCacheUpdateExceptions(Table.java:1767)
    at com.vaadin.ui.Table.refreshRenderedCells(Table.java:1756)
    at com.vaadin.ui.Table.attach(Table.java:4290)
    at com.vaadin.server.AbstractClientConnector.attach(AbstractClientConnector.java:619)
    at com.vaadin.ui.AbstractComponent.attach(AbstractComponent.java:675)
    at com.vaadin.ui.AbstractComponent.setParent(AbstractComponent.java:582)
    at com.vaadin.ui.AbstractSingleComponentContainer.setContent(AbstractSingleComponentContainer.java:150)
    at com.vaadin.ui.UI.setContent(UI.java:1312)
    at com.example.gridbutton.GridbuttonUI.init(GridbuttonUI.java:103)
    at com.vaadin.ui.UI.doInit(UI.java:682)
    at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:214)
    at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1409)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:364)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodException: org.vaadin.viritin.ListContainer.getCollection()
    at org.vaadin.viritin.ListContainer$DynaBeanItem$DynaProperty.getValue(ListContainer.java:545)
    at com.vaadin.ui.Table.formatPropertyValue(Table.java:4170)
    at com.vaadin.ui.Table.getPropertyValue(Table.java:4114)
    at com.vaadin.ui.Table.parseItemIdToCells(Table.java:2386)
    at com.vaadin.ui.Table.getVisibleCellsNoCache(Table.java:2225)
    at com.vaadin.ui.Table.refreshRenderedCells(Table.java:1745)
    ... 35 more

I’m not sure where to go from here. I think I don’t know what I’m doing to be honest.

Hi Alisa,
This may be found helpful for you. https://www.youtube.com/watch?v=bH2_nWxwXY8