Java collections, table lookups, servlet context

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));
      };

}
LVL 2
PaullkhaAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
MogalManicConnect With a Mentor Commented:
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
 
CEHJCommented:
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
 
TimYatesConnect With a Mentor Commented:
>  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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
TimYatesCommented:
Sorry...

     public static DivisionsBranchesLU instance = null ;

should be

     private static DivisionsBranchesLU instance = null ;

:-)
0
 
PaullkhaAuthor Commented:
>>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
 
TimYatesCommented:
> How would I then instantiate this class, or better, load values from database?

DivisionsBranchesLU divbLU = DivisionsBranchesLU.getInstance() ;
0
 
CEHJCommented:
>>The values hopefully will come from sql table

Yes, i see - i was wondering about that.
0
 
TimYatesCommented:
> 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
 
CEHJConnect With a Mentor Commented:
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
 
CEHJCommented:
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
 
TimYatesCommented:
> 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
 
CEHJCommented:
I'd be sending back my Tomcat if it did ;-)
0
 
PaullkhaAuthor Commented:
Whoa, went a little behind my skills, need to reread this a few more times. Went away for few days.
0
 
PaullkhaAuthor Commented:
>>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
 
PaullkhaAuthor Commented:
With this code change:
private DivisionsBranchesLU()

this stmt still actually works.....?
DivisionsBranchesLU divbLU = new DivisionsBranchesLU();
0
 
TimYatesCommented:
> this stmt still actually works.....?

From inside the same class...

Therefore you can see private methods...
0
 
PaullkhaAuthor Commented:
Nevermind, moved main to seperate test class...
0
 
TimYatesCommented:
:-)
0
 
PaullkhaAuthor Commented:
Is this type of model a "best practice" for retrieving and storing table lookup values?

Whoa, that was fast... ;)
0
 
CEHJCommented:
>>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
 
CEHJCommented:
8-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.