Solved

Java collections, table lookups, servlet context

Posted on 2004-08-25
21
304 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
 
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This video teaches viewers about errors in exception handling.

708 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now