Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Java collections, table lookups, servlet context

Posted on 2004-08-25
21
Medium Priority
?
314 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 300 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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 300 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 100 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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 tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

636 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