Solved

Java collections, table lookups, servlet context

Posted on 2004-08-25
21
306 Views
Last Modified: 2013-11-24
I created a class that will read the following table:
Div                  Branch
Buick               NY
Buick               DAL
Buick               ATL
CADILLAC        NY
CADILLAC        DAL
CADILLAC        TOR
CHEVY             FLA

I will put this class on the server context when app is started.
What are my next steps? Should this work?

1) I want to prevent users from doing this:
mydivblu =  new DivisionsBranchesLU().
Only one class on app startup should instantiate this class. From then on, it will be passed by server context variable.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
*/
public class DivisionsBranchesLU {
      private Map listDivisions = new HashMap();
      private List branches = new ArrayList();
      private Map branchesByDivision = new HashMap();

      public DivisionsBranchesLU()
      {
            loadBranches();
            loadBranchesbyDivision();
      }
      /**
       * Call this function to load branches for a given division
       *
       */
      private void loadBranchesbyDivision()
      {
            //Select branches, divisions from table order by divisions.
            //Loop through rs
            List branchesThisDivision = new ArrayList();
      
            branchesThisDivision.add("NY");
            branchesThisDivision.add("DAL");
            branchesThisDivision.add("ATL");
            branchesByDivision.put("BUICK",branchesThisDivision);

            branchesThisDivision = new ArrayList();
            branchesThisDivision.add("NY");
            branchesThisDivision.add("DAL");
            branchesThisDivision.add("TOR");
            branchesByDivision.put("CADILLAC",branchesThisDivision);
      
            branchesThisDivision = new ArrayList();
            branchesThisDivision.add("FLA");
            branchesByDivision.put("CHEVY",branchesThisDivision);

      }

      private void loadBranches()
      {
            //Select distinct branches from table
            branches.add("FLA");
            branches.add("DAL");
            branches.add("ATL");
            branches.add("TOR");
            branches.add("NY");
      }

      public List getBranches()
      {
            //just return all branches
            return branches;
      }
      public List getBranches(String keyOnDivision)
      {
            //for a given Division (key) return branches for that division
            return (List)branchesByDivision.get(keyOnDivision);
      }
      public List getBranches(String[] keysOnDivision)
      {
            //for a given array of keys, return list of branches for these division
            Set branchesByDivisions = new HashSet(); //make sure unique, use set
            List uniqueBranches = new ArrayList();
            for (int i = 0; i< keysOnDivision.length; i++)
            {
                  System.out.println(keysOnDivision[i]);
                  branchesByDivisions.addAll((List)branchesByDivision.get(keysOnDivision[i]));
            }
            uniqueBranches.addAll(branchesByDivisions);
            return uniqueBranches;
      }
      
      public static void main(String[] args)
      {
            DivisionsBranchesLU divbLU = new DivisionsBranchesLU();
            List allbranches = divbLU.getBranches();
            //System.out.println(allbranches);
            System.out.println("BUICK:" + divbLU.getBranches("BUICK"));
            System.out.println("CHEVY:" + divbLU.getBranches("CHEVY"));
            String[] divisions = {"CHEVY","BUICK"};
            System.out.println(divbLU.getBranches(divisions));
      };

}
0
Comment
Question by:Paullkha
  • 7
  • 7
  • 6
  • +1
21 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11893025
Looks ok on a fairly quick glance, apart from the fact that you should program for extensibility by reading values that are currently hard-coded from config files instead
0
 
LVL 35

Assisted Solution

by:TimYates
TimYates earned 75 total points
ID: 11893131
>  1) I want to prevent users from doing this:
>  mydivblu =  new DivisionsBranchesLU().
>  Only one class on app startup should instantiate this class. From then on, it will be passed by server context variable.

change:

     public DivisionsBranchesLU()
     {
          loadBranches();
          loadBranchesbyDivision();
     }

to

     public static DivisionsBranchesLU instance = null ;
     private DivisionsBranchesLU()
     {
          loadBranches();
          loadBranchesbyDivision();
     }
 
     public DivisionsBranchesLU getInstance()
     {
          if( instance == null )
               instance = new DivisionsBranchesLU() ;
          return instance ;
     }
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11893141
Sorry...

     public static DivisionsBranchesLU instance = null ;

should be

     private static DivisionsBranchesLU instance = null ;

:-)
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 2

Author Comment

by:Paullkha
ID: 11893461
>>TY
     public static void main(String[] args)
     {
          DivisionsBranchesLU divbLU = new DivisionsBranchesLU();
>> private static DivisionsBranchesLU instance = null ;
How would I then instantiate this class, or better, load values from database?

>>CEHJ
 reading values that are currently hard-coded from config files instead
The values hopefully will come from sql table.(as per sr mngmt, don't see why since this table is not changing anytime soon). Contrived example. using sql in test case is just a mess.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11893512
> How would I then instantiate this class, or better, load values from database?

DivisionsBranchesLU divbLU = DivisionsBranchesLU.getInstance() ;
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11893558
>>The values hopefully will come from sql table

Yes, i see - i was wondering about that.
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 75 total points
ID: 11893999
The pattern that  TimYates is the singleton pattern.  Using the singleton pattern guarantees that there will ONLY be one instance of the class per VM.  All access is through the static getInstance() method.  The first thread to call getInstance() will allocate the instance.  Any successive threads(users) will call getInstance() which will return the initial instance.

Using this pattern, you are not requiring that the instance be stored on the Application Context.  You can still do so if the application context is accessable easier from withing JSP.

Slight change to the example should change the getInstance to syncronized and static:
    syncronized public static DivisionsBranchesLU getInstance()
     {
          if( instance == null )
               instance = new DivisionsBranchesLU() ;
          return instance ;
     }
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11894070
> Slight change to the example should change the getInstance to syncronized and static:
 
Doh! forgot the static bit ;-)

And synchronized is a good idea...  whoops ;-)
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 25 total points
ID: 11894192
synchronization is probably unnecessary since (afaik) this is read-only. If so, to underline the point and protect your collections, you can use:

return Collections.unmodifiableList(uniqueBranches);

and similar for other collection types
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11894250
In fact that last point probably obviates the need for a singleton too. What does it matter if there is more than one instance knocking around by some classloading quirk if the collections are read-only and unmodifiable?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11894361
> What does it matter if there is more than one instance knocking around by some classloading quirk if the collections are read-only and unmodifiable?

Could it cause memory issues if it went a bit mad and loaded thousands of them?

Spose not...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11894379
I'd be sending back my Tomcat if it did ;-)
0
 
LVL 2

Author Comment

by:Paullkha
ID: 11962651
Whoa, went a little behind my skills, need to reread this a few more times. Went away for few days.
0
 
LVL 2

Author Comment

by:Paullkha
ID: 11962703
>>obviates the need for a singleton too
But every time it is instatiated, since this will be reading from database, means new connection pool started, another database read, hundreds of times, yes?
(right now this is actually what is happening, connection being created, table being read, in serveral dozen servlets and jsp pages, hundreds of times, for hundres of users...bad)
0
 
LVL 2

Author Comment

by:Paullkha
ID: 11962814
With this code change:
private DivisionsBranchesLU()

this stmt still actually works.....?
DivisionsBranchesLU divbLU = new DivisionsBranchesLU();
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11962847
> this stmt still actually works.....?

From inside the same class...

Therefore you can see private methods...
0
 
LVL 2

Author Comment

by:Paullkha
ID: 11962872
Nevermind, moved main to seperate test class...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11962930
:-)
0
 
LVL 2

Author Comment

by:Paullkha
ID: 11962937
Is this type of model a "best practice" for retrieving and storing table lookup values?

Whoa, that was fast... ;)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11966888
>>But every time ... yes?

You just need to set a servlet to load it at startup. It shouldn't really be loaded more than once, but you can easily put a small debug, or better, log statement in there so you can see when it's loaded
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12009355
8-)
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ArrayIndexOutOfBoundException 9 82
stackato and cloud 4 85
Tomcat: Unable to run tomcat service. 2 20
Java: The Public Class Main 4 16
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question