LVOOP Factory Pattern

Factory Pattern..
I am using factory pattern for its advantage of loading classes into memory when it is called dynamically.
But I am able to see all the classes loaded into memory by looking into LabVIEW Class Hierarchy window and VI Hierarchy window.
Where this not happen. Please suggest solution for this query.
nilesh
Attachments:
Factory Pattern.zip ‏136 KB

I'll reply but I am no OOPer expert.
THe factory pattern as implemented in LV is just anum driven case structure where each case can have a different instance of a class constant. All of the Class constants exit through the same tunnel that LV cast as the common ancestor class of all of the constants in the case structre.
The exiting wire can be wired to any method available for the common parent class.
So it is a code construct that lets you choose the type of data on the wire.
The Actor Frame work is another fancy term for a generic barckground task.
Actors can be instaciated using using teh Factory Pattern to choose the "flavor" of background task.
Re: All in memory
If the classes are in the project and the project is open then all of the classes are loaded to make sure they are healty.
In an exe that is not always the case as is the situation when the classes are not part of the project or the project is closed.
This image (and the others in that album) show a method I used to find and use compatable classes to create the background task (Active Object).
Active Object (as I understand them) are instances of a Class that function indepenently once created and provided a method to allow other objects to invoke its exposed methods.
Example DAQ_Collector
Child of an I/O class that runs in the background and acepts commands(invoked methods) like "Start", Stop, Exit.
I will now step back to let those who know more correct what I havge posted.
Have fun!
Ben
Ben Rayner
I am currently active on.. MainStream Preppers
Rayner's Ridge is under construction

Similar Messages

  • Help building an executable that uses a factory pattern

    Hello,
    I'm trying to build an .exe from a VI that uses the factory pattern. The VI gives me the error that it can't find the classes to load and is looking outside the .exe file to find them. The specific error is:
    "Get LV Class Default Value.vi<APPEND>
    <b>Complete call chain:</b>
         Get LV Class Default Value.vi
         Main.vi
    <b>LabVIEW attempted to load the class at this path:</b>
    C:\ATE\Experiments\Build Testing\Builds\Virtual Classes\High Class\High Class.lvclass"
    I thought those classes were bundled into the .exe when it was built? I have included the class folders in the "Always Included" window of the build script.
    Any help would be appreciated. I'm fairly new to classes and I haven't built an .exe with an app using the factory pattern.
    Thanks,
    Simon
    Attachments:
    Build Testing.zip ‏491 KB

    This might be the answer.  I found the following checklist on Building Executables.  It really is referencing things other than Objects, but maybe Object folders also need to be properly located ...
    Bob Schor  [the stuff I found is below this line ...]
    Ensure paths generate correctly.
    Details
    If a VI loads other VIs dynamically using VI Server or calls a dynamically loaded VI through a Call By Reference node, make sure the application or source distribution creates the paths for the VIs correctly. To ensure paths generate correctly, use relative paths to load the VIs. The following table depicts the relative paths for a top-level VI, foo.vi, which calls a.vi and b.vi. C:\..\Application.exe represents the path to the application.
    Path to source files
    Path to files in application
    C:\Source\foo.vi
    C:\..\Application.exe\foo.vi
    C:\Source\xxx\a.vi
    C:\..\Application.exe\xxx\a.vi
    C:\Source\yyy\b.vi
    C:\..\Application.exe\yyy\b.vi
    If you use the LabVIEW 8.x file layout and you include dynamically loaded VIs in the application, the paths to the VIs change. For example, if you build b.vi into an application, its path is C:\..\Application.exe\b.vi whereC:\..\Application.exe represents the path to the application and its filename.

  • Problems with Factory pattern

    Sorry... I know this topic has been done to death but I still have some questions.
    In my development, I keep encountering a recurring problem that I believe should be solved by the 'factory pattern'. (Note: I'm not a patterns nut so I am only guessing about the correct pattern).
    Here is the problem:
    I develop an abstract base class. I extend the base class with several subclasses. Exterior objects use the instances via a base class reference and I don't want to them to have to know which is the correct subclass or how to create the instance.
    My solution is to make a create(param, param,...) method in the base class and using the param(s) construct the instance something like:static Foo create(int type)
    Foo instance = null;
    String className = "com.myco.foos.DefaultFoo";
    if(CONST_A == type)
      className = "com.myco.foos.FooA";
    else if(CONST_B == type)
      className = "com.myco.foos.FooB";
    {on and on...}
    {using reflection create a new instance from the className String}
    return instance;
    }The obvious problem with the create() method is that it becomes a maintenence point and I don't like the idea of a base class knowing about subclasses.
    Anyone know better a solution? Comments?
    Thanks in advance.

    Yes, that is the Factory pattern you describe. The client programs are going to call your createFoo() method and get back an instance of a subclass of Foo. Typically this pattern is used where there is some external entity that determines what subclass will be returned -- for example a system property -- and the client programs call createFoo() with no arguments. In this case reflection is used to create the instance, and your base class does not need to know anything about any subclasses.
    However, if your client programs can influence the choice of subclass, then they will have to pass some kind of parameter into createFoo(). At this point, createFoo() requires some decision logic that says "create this, or that, depending on the input parameter". And if that parameter is simply a code that enables the client programs to say "Give me a ChocolateFoo instance", then returning "new ChocolateFoo()" is the most straightforward design. But in this case, why can't the client program do that?
    If you don't like the base class having to know about subclasses (and you shouldn't be happy if it does), then you could have a helper class -- FooFactory -- that contains only the static method createFoo(). This class would know about Foo, and about any of its subclasses that it can produce instances of. It's still a maintenance point, no avoiding that, but at least it is off by itself somewhere.

  • Factory pattern question

    Hi, I'm using a factory pattern to return different objects depending on whats needed:
    synchronized Worker getWorker(final byte[] request, String type) {
            int poolIndex = -1;
            for (int i = 0; i < workerCount; i++) {
                if (workerPool[i] == null) {
                    poolIndex = i;
                    if (type.equals("TypeA")) {
                        workerPool[i] = new TypeA(request, poolIndex);
                        workerPool.setType("TypeA");
    } else if (type.equals("TypeB")) {
    workerPool[i] = new TypeB(request, poolIndex);
    workerPool[i].setType("TypeB");
    return workerPool[poolIndex];
    return null;
    My problem is that they return ok, however. If TypeA has a function called Test1. and TypeB has a function Test6. If I try Worker.Test6 it wont recognise it. Is this just my ignorance? Should both just contain the same methods as Worker and override them?

    Hi, I'm using a factory pattern to return different
    objects depending on whats needed:
    synchronized Worker getWorker(final byte[] request,
    String type) {
    int poolIndex = -1;
    for (int i = 0; i < workerCount; i++) {
    if (workerPool[i] == null) {
    poolIndex = i;
    if (type.equals("TypeA")) {
    workerPool[i] = new
    workerPool[i] = new TypeA(request, poolIndex);
    workerPool.setType("TypeA");
    } else if (type.equals("TypeB")) {
    workerPool[i] = new
    workerPool[i] = new TypeB(request, poolIndex);
    workerPool[i].setType("TypeB");
    return workerPool[poolIndex];
    return null;
    My problem is that they return ok, however. If TypeA
    has a function called Test1. and TypeB has a function
    Test6. If I try Worker.Test6 it wont recognise it. Is
    this just my ignorance? Should both just contain the
    same methods as Worker and override them?
    indeed, the factory pattern is intended to shield the user code from implementation details of the returned interface. It (ie. the user code) MUST NOT know about which actual implementations it receives, otherwise, the factory has no use.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Factory Patterns with Generics

    I am trying to combine the good old factory pattern with generics and could use some advice.
    I have the following
    //Base class from which all my things extend
    public abstract class Thing {
    //one kind of thing
    public class ThingOne extends Thing {
    //another kind of thing
    public class ThingTwo extends Thing {
    //interface for my factory
    public interface ThingFactory<T> {
    public T create(long id);
    //a factory for thingones
    public class ThingOneFactory<T> implements ThingFactory<T> {
    public T create(long id) {
    return (T) new ThingOne();
    public class TestClass{
    public <T extends Thing> T getThing(ThingFactory<T> tf){
    //do a bunch of generic stuff to figure out id to call create
    ThingFactory<T> instance = tf;
    return (T) instance.create(Long id);
    }My calling code would know what kind of thing it needs but necessarily the things id. Which can be computed in a generic way.
    TestClass gt = new TestClass();
    gt.getThing(new ThingOneFactory<ThingOne>());This all seems to work properly but I am getting "Type safety: Unchecked cast from ThingOne to T" in my ThingOneFactory
    My T's will always extend Thing, what am I missing? Is there a better way to do this?
    Edited by: nedry on Dec 29, 2009 5:39 PM

    I thought of that after I posted. But that just moves my unsafe cast warning into TestClass.Why?
    return (T) instance.create(Long id);That can't have ever compiled. What is the exact code? And why did you have to cast (what was the warning/error)?

  • Builder vs Factory Patterns

    Hi,
    I read about builder and factory patterns. But both of them look quite similar.
    Can u plz help me to understand the difference between them.
    Thanking You,
    Chamal.

    I puzzled over this too. The UML is almost identical for both patterns. A great example of how UML class diagram leave a lot to be desired.
    This is my take, which may not be absolutely correct or orthodox.
    The difference is that in the abstract factory, the point is to hide the implementation of the abstract type. In the builder it's other way around. The point is to hide the implementation of the callers of the builder or really, what is being built.
    So a user of a abstract factory should not know (or care) about what type the abstract factory returns. In the builder pattern, the code could potentially make references to specific builder types (a text builder for debugging or console mode, for example) but the implementation of what is being built is not known to the builder.
    You can easily combine the two and get a lot of flexibility.

  • RMI & Factory Patterns

    Hey,
    I'm developing a Chat RMI app for a college assignment. One of the features that's required is to use the Factory Pattern(FP). I've read about Factory patterns and have a bit of an understanding of them but I'm not sure what I developed actually implements a FP. Would the code below be considered a Factory Pattern?
    I've created an interface class called ChatServer and a class which implements this interface called ChatServerImpl. The server with the main method is as follows:
    public class Server {
      public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
          System.setSecurityManager(new RMISecurityManager());
        try {
          ChatServerImpl server = new ChatServerImpl();
          Naming.rebind("DSChat",server);
          System.out.println("DSChat bound in registry");
        catch (RemoteException remoteExc) {
          remoteExc.printStackTrace();
        catch(MalformedURLException malformedURLExc){
          malformedURLExc.printStackTrace();
      }I have a ChatServer, the interface class, object in the Client UI class that calls the server methods, e.g.
    ClientUI
    public class ClientUI extends JApplet implements ActionListener, ClientMonitor
         ChatServer server;
         public void init()
              try
                   server = (ChatServer) Naming.lookup("//" + getCodeBase().getHost()
                             + "/" + serviceName);
              catch (NotBoundException notBoundExc)
                   notBoundExc.printStackTrace();
              catch (MalformedURLException malformedURLExc)
                   malformedURLExc.printStackTrace();
              catch (RemoteException remoteExc)
                   remoteExc.printStackTrace();
         public void start()
              try
                   authenticate = server.authenticate(sessionUser);
              catch (RemoteException remoteExc)
                   remoteExc.printStackTrace();
              if (authenticate)
                   this.componentInit();
                   this.layoutComponents();
                   try
                        UnicastRemoteObject.exportObject(this); // Allow server to
                        // connect.
                        server.registerClient(this);
                   catch (RemoteException remoteExc)
                        remoteExc.printStackTrace();
              else
                   String errMsg = "Sorry you are already logged on to this chat room";
                   JOptionPane.showMessageDialog(this, errMsg, "You're already here",
                             JOptionPane.OK_OPTION);
                   server = null;
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnSend)
              {//Checks if textbox is empty
              if (txtInput.getText().compareTo("") != 0)
                   String input = txtInput.getText();
                   txtInput.setText(""); // Clear text field.
                   txtInput.requestFocus();
                   Message msg = new Message(input);
                   server.sendMessage(msg);               
         public void receiveMessage(Message msg)
              // Display received message.
              txtMessages.setText(txtMessages.getText() + "\n" + msg.toString());
              txtMessages.setCaretPosition(txtMessages.getText().length());
    ChatServer Interface
    //Interface
    public interface ChatServer extends Remote{
      public void sendMessage(Message msg) throws RemoteException;
      public boolean authenticate(ChatUser usr) throws RemoteException;
    ChatServerImpl
    public class ChatServerImpl extends UnicastRemoteObject implements ChatServer
         public ChatServerImpl() throws RemoteException
              super();
         public boolean authenticate(ChatUser usr) throws RemoteException
              ClientMonitor client = registeredUsersTMap.get(usr.getUsername());
              if (client == null)
                   return true;
              return false;
          * ChatServer interface method implementation. Sends messages between two
          * users.
         public void sendMessage(Message msg) throws RemoteException
              //Thread sends message to client
              SendMessageThread sendMessage = new SendMessageThread(
                        this.roomUsersHMap, this.registeredUsersTMap, msg);
              Thread tSendMsg = new Thread(sendMessage);
              tSendMsg.run();
    }Any help would be appreciated.

    Question: Does the code compile and run properly?
    Since the Gang of Four published their pattern book, everyone is obsessed with patterns.
    A factory basically creates and returns a new object. The following does that and technically could be called a factory.
    public MyObject createA() {};Just what object does your code create and return to the caller?

  • Difference between Builder Pattern and Factory Pattern

    difference between Builder Pattern and Factory Pattern

    You are right Both of these patterns are creational design patterns Purpose of these two patterns is very different as Abstract Factory Patterns (which is commonly known as Factory pattern ) is used to create a object in a scenario when you have a product & there is a possibility of many vandors providing implementation for it. So it is good to come up with a abastract factory which provides create method for the product. Each vendor can implement you abstract factory & provide a concrete implementation which will return a product of Vendor implementation.
    Builder patter is used in case you have a very complex object creation process involved & you realy want to abstract the client from doing all those complex steps. In such situation you create a builder class which takes care of all complex steps & client just needs to use this builder class to create your complex object.
    Hope it clarifies your doubts.

  • Need a little help with this factory pattern thing..

    Evening all,
    I have an assignment to do over easter, before i start i will say i dont want any code or anything so this isnt 'cheating' or whatever..
    This was the brief:
    A vending machine dispenses tea and coffee, to which may be added milk, and 0, 1 or 2 doses of sugar. When the machine is loaded it initially contains 100 doses of tea, 100 doses of coffee 50 doses of milk and 70 doses of sugar. After it has been in use for a while it may run out one or more items. For example, it may run out of sugar, in which case it would continue to vend tea, coffee, tea with milk, and coffee with milk. Periodically, an attendant recharges the machine to full capacity with doses of coffee, tea, milk and sugar. A user selects the required beverage, selects the required amount of sugar, and selects milk if required. The machine responds with a message telling the user the cost of the drink (coffee is 30P, tea 20P, milk 10P, and sugar 5P per dose). The user inserts coins (the machine accepts 10P and 5P coins), and when the required sum or more has been inserted, the machine dispenses the beverage, and possibly some change.
    You are to write a program that simulates the above vending machine. Your solution must use the class factory pattern, and make use of the code templates provided. The user interface should be constructed with a Swing JFrame object.
    We were suppled with code for all of the classes required except for the JFrame.. They are as follows:
    public abstract class Beverage
      int sugar;
      boolean milk;
      public String getMessage()
        String name = this.getClass().getName();
        String sugarMessage = "";
        if (sugar == 1) sugarMessage = "one sugar";
        if (sugar == 2) sugarMessage = "two sugars";
        if (sugar == 0) sugarMessage = "";
        return  "Vended 1 " + name  +  (milk ? " with milk " : "") + (sugar==1 || sugar == 2 ? (milk ? "and " + sugarMessage : " with " + sugarMessage) : "");
    public class Coffee extends Beverage
      public Coffee( int sugar, boolean milk)
        this.sugar = sugar;
        this.milk = milk;
    public class Tea extends Beverage
      public Tea(int sugar, boolean milk)
        this.sugar = sugar;
        this.milk = milk;
    public class SugarButtonsGroup
      private JRadioButton jRadioButton0Sugar = new JRadioButton();
      private JRadioButton jRadioButton1Sugar = new JRadioButton();
      private JRadioButton jRadioButton2Sugar = new JRadioButton();
      private ButtonGroup sugarButtons = new ButtonGroup();
      public SugarButtonsGroup()
        jRadioButton0Sugar.setText("No sugar");
        jRadioButton1Sugar.setText("1 sugar");
        jRadioButton2Sugar.setText("2 sugars");
        sugarButtons.add(this.jRadioButton0Sugar);
        sugarButtons.add(this.jRadioButton1Sugar);
        sugarButtons.add(this.jRadioButton2Sugar);
      public int numberOfSugars()
        if (this.jRadioButton1Sugar.isSelected()) return 1;
        if (this.jRadioButton2Sugar.isSelected()) return 2;
        return 0;
      public ButtonGroup getButtonGroup()
        return sugarButtons;
      public JRadioButton getJRadioButton0Sugar()
        return jRadioButton0Sugar;
      public JRadioButton getJRadioButton1Sugar()
        return jRadioButton1Sugar;
      public JRadioButton getJRadioButton2Sugar()
        return jRadioButton2Sugar;
    public class BeverageButtonsGroup
      private JRadioButton jRadioButtonTea = new JRadioButton();
      private JRadioButton jRadioButtonCoffee = new JRadioButton();
      private ButtonGroup buttonGroup = new ButtonGroup();
      public BeverageButtonsGroup()
        buttonGroup.add(jRadioButtonTea);
        buttonGroup.add(jRadioButtonCoffee);
        jRadioButtonTea.setText("Tea");
        jRadioButtonCoffee.setText("Coffee");
        jRadioButtonCoffee.setSelected(true);
      public String getBeverageName()
        if (jRadioButtonTea.isSelected()) return "tea";
        if (jRadioButtonCoffee.isSelected()) return "coffee";
        return "";
      public ButtonGroup getBeverageButtonGroup()
        return buttonGroup;
      public JRadioButton getJRadioButtonTea()
        return jRadioButtonTea;
       public JRadioButton getJRadioButtonCoffee()
        return jRadioButtonCoffee;
    public class MilkCheck
      private JCheckBox jCheckBoxMilk = new JCheckBox();
      public MilkCheck()
        this.jCheckBoxMilk.setText("Milk");
      public JCheckBox getJCheckBoxMilk()
        return jCheckBoxMilk;
      public boolean withMilk()
        return this.jCheckBoxMilk.isSelected();
    public class CoinMechanism
      private JButton jButton5P = new JButton();
      private JButton jButton10P = new JButton();
      private JTextField jTextFieldTotal = new JTextField();
      private BeverageFactory b;
      public CoinMechanism (BeverageFactory b)
        this.b = b;
        reset();
        jTextFieldTotal.setEditable(false);
        jButton5P.setText("Insert 5 pence");
        jButton5P.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
              jButton5P_actionPerformed(e);
        jButton10P.setText("Insert 10 pence");
        jButton10P.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
              jButton10P_actionPerformed(e);
      private void jButton5P_actionPerformed(ActionEvent e)
        // to be completed
      private void jButton10P_actionPerformed(ActionEvent e)
        // to be completed
      private void notifyVend()
        b.getCoinCurrentTotal(jTextFieldTotal.getText());
      public void reset()
         this.jTextFieldTotal.setText("0");
      public JButton getJButton5P()
        return this.jButton5P;
      public JButton getJButton10P()
        return this.jButton10P;
      public JTextField getJTextFieldTotal()
        return this.jTextFieldTotal;
    public class BeverageFactory
      private int coffees;
      private int teas;
      private int milks;
      private int sugars;
      public BeverageButtonsGroup beverageButtons = new BeverageButtonsGroup();
      public SugarButtonsGroup sugarButtons = new SugarButtonsGroup();
      public MilkCheck milkCheck = new MilkCheck();
      public CoinMechanism slots = new CoinMechanism(this);
      public void setUIState()
        // sets the states of the widgets on the frame accoording to the
        // quantities of supplies in the machine
        // to be finished
      public void getCoinCurrentTotal (String o)
        // this is should be executed whenever a user puts a coin into the machine
        int foo = Integer.parseInt(o);
        // to be finished
      private int cost()
        // returns the cost of the currently selected beverage
        // to be finished
      public BeverageFactory( int coffees, int teas, int milks, int sugars)
        this.coffees = coffees;
        this.teas = teas;
        this.milks = milks;
        this.sugars = sugars;
      public void refill(int coffees, int teas, int milks, int sugars)
        // to be completed
      public Beverage makeBeverage(String name, boolean milk, int sugar)
        if (name.compareTo("coffee") == 0)
          coffees--;
          if (milk) milks--;
          sugars = sugars - sugar;
          return new Coffee(sugar,milk);
        if (name.compareTo("tea") == 0)
          teas--;
          if (milk) milks--;
          sugars = sugars - sugar;
          return new Tea(sugar, milk);
        return null;
    }Okay, well if you read through all that, blimey thanks a lot!.
    My question relates to this method in the BeverageFactory class:
    public void getCoinCurrentTotal (String o)
        // this is should be executed whenever a user puts a coin into the machine
        int foo = Integer.parseInt(o);
        // to be finished
      }I don't understand what the heck its supposed to be for..
    I can obtain the current amount of coins inserted from the textbox in the CoinMechanism class. The only thing i could think of, would be for this to enable the 'Vend' button, but it doesnt have access anyway..
    Any suggestions would be hugely appreciated, I have tried to contact the lecturer but he isnt around over easter i guess..
    Many thanks.

    I'm not going to read all that, and I don't do GUIs, so this is just a guess, but it looks like the CoinMechanism class is intended to be just a dumb processor to accept coins and determine what each coin's value is, but no to keep a running total.
    That in itself is an arguably acceptable design--one class, one job and all that. But I don't know that it makes sense to have the BeverageFactory keep the running total.
    Overall, I gotta say, I'm not impressed with your instructor's framework. Maybe it's just because I didn't look at it closely enough, or maybe it's more of a naming problem than a design problem, but it seems to me he's mixing up GUI code with business logic.
    Good luck.

  • BlazeDS and Abstract Factory Pattern

    Hi All,
    I was trying to extend my application using the Factory Method. But, I identified that I need to use an abstract Factory pattern to meet my design requirements. In other words I need to create a FactoryInstance based on a input. Will that be possible.
    Any help?????
    -Ram V

    The Factory pattern is meant to give you the ability to generically construct objects (rather than explicitly declare what you want to create via the "new" keyword you defer to a factory and take what it gives you) The Abstract Factory pattern is meant to give you the ability to generically construct Factories. So, for instance, say you want to create widgets with a certain look and feel. You could use the Factory pattern and ask a ButtonFactory to make buttons and a TextArea factory to make TextAreas, but since you want the same look and feel for all widgets you could just ask the WidgetFactory to give you a WidgetFactory for a given Look and Feel and then ask it to make Buttons and TextAreas and whatever else, knowing that it has handled which kind of button and whatever else you need.
    Hope that made sense, good luck
    Lee

  • Beginner Factory Pattern help needed please

    hi people,
    Can someone please explain to me in laymans terms what the use of the Factory pattern is. I went to http://www.research.umbc.edu/~tarr/dp/lectures/Factory.pdf
    and it did nit help me too much.
    I'd really appreciate it if someone could give me an abstract example of when the Factory pattern would be useful. The reason I ask is because I am researching into JDO and have come across PersistenceManagerFactory and think I would underdstand this better if I understand Factory's.
    Many thanks.

    Is the reason for the ConnectionHelper to allow us to use that as the return type in the getHelper() method, thus allowing us to have either the OracleConnectionHelper or DB2ConnectionHelper?
    Yes. You want to achieve polymorphism. You are interested in the connect() method, not necessarily what database is used (not the best example in the world, normally you would care as different vendors have slightly different SQL syntax, but assume you were using no triggers, procedures or non-ANSI SQL).
    So, are you basically saying that a Factory is a class that can be used to decide which of the two databases we are going to connect to?
    Depends. In this instance, you name the database you want and the factory is responsible for returning the proper class. In other cases, you might have developed a program that works across databases and only uses one at a time. In this case, you would probably read in a setting at application startup, and the factory would always return the same object type.
    If there is a PersistentManagerFactory, does it mean this would be used to decide what PersistentDataStore we are going to use (i.e. flat file, database, serialised object etc)?
    Again, it depends. You can make your factories 'smart' by deciding where to serialize a given object (say, every domain model object has a method save() and your DAO uses the factory to get a connection to do its work). In other cases, you have a 'bare-bones' factory that simply returns the requested object type. Why go through all that effort? Well, one advantage is that I can put the factory, interface and any implementations in the same package. The only ones that (normally) would need to be public would be the interface and the factory. You can hide the implementation details using the security features of the language.
    Also, why is OracleConnectionHelper a final class?[i]
    In general, I make all variables, method signature parameters and classes final. Once I need to sub-class or re-assign a variable value, I remove the final clause. I can't count the number of times the compiler caught an error (rather than at runtime) because of the additional 'safety' declaring everything final gives you. Only make variables and classes (and method signature variables) non-final when you need to. IMHO, of course.
    - Saish

  • My Factory Pattern

    Here is the factory pattern I have implemented. I want to know, exactly which pattern this belongs to. I liked this. Comments and suggestions are welcome.
    // ViewFactory.java
    // Implementation of the Class ViewFactory
    // Generated by Enterprise Architect
    // Created on: 9/28/02
    // Original author: Vijendra Kotian
    // Modification history:
    public class ViewFactory implements ViewFactoryInterface {
         private ViewFactoryInterface vf;
         protected ViewFactory(){
         public ViewFactory(String type){
              System.out.println("ViewFactory created");
              vf=createNewView(type);
         public void finalize() throws Throwable {
              super.finalize();
         private ViewFactoryInterface createNewView(String type){
              char c=(char)type.charAt(0);
              switch(c){
              case 'a':
              case 'A':
                   return new AWTViewFactory();
              case 'm':
              case 'M':
                   return new MotifViewFactory();
              return null;
         public void openView(ViewFactoryInterface param){
              vf=param;
         public void print(){
              if(vf!=null) vf.print();
              else System.out.println("Vf is null!!!");
         public static void main(String[] s){
              ViewFactoryInterface vf=new ViewFactory("MOTIF");
              vf.print();
              ViewFactoryInterface vf1=new ViewFactory("Awt");
              vf1.print();
              vf1.openView(vf);
              vf1.print();
              ViewFactoryInterface vf2=new ViewFactory();
              vf2.print();
    public interface ViewFactoryInterface {
         public void print();
         public void openView(ViewFactoryInterface vfi);
    import ViewFactory;
    public class MotifViewFactory extends ViewFactory{
         public MotifViewFactory(){
              //super("Motif");
              System.out.println("New Motif view factory created");
         public void finalize() throws Throwable {
              super.finalize();
         public void print(){
              System.out.println("Motif print");
    import ViewFactory;
    public class AWTViewFactory extends ViewFactory{
         public AWTViewFactory(){
              //super("AWT");
              System.out.println("Awt View Factory created");
         public void finalize() throws Throwable {
              super.finalize();
         public void print(){
              System.out.println("AWT Print");
    -Vijendra K

    http://forum.java.sun.com/faq.jsp#messageformat

  • Singleton pattern over Factory pattern

    What is the difference between the Factory and Singleton pattern.
    Can we use a singleton (pattern) class to create other object instances and return them.
    What are the advantages and disadvantages for using the Singleton pattern here.
    Or do we have to use only a factory (pattern) class to do the above type of task.

    The Factory pattern and the Singleton pattern are used to achieve different things. That's not to say they can't be used together. A Singleton pattern is used to force the use of a single instance of a class, hence the name. The Factory pattern is used to determine at runtime what class will be used.

  • Double Factory pattern purposal as replacement for Double Check #2

    Hi All,
    Here is the code for the pattern proposal, its intended as a replacement for double checked locking, which was proved to be broken in 2001. Here is the code...
    public class DoubleFactory {
       private static Object second_reference = null;
       public static Object getInstance() {
          Object toRet = second_reference;
             if (toRet == null) {
                second_reference = CreationFactory.createInstance();
                toRet = second_reference;
          return toRet;
       private DoubleFactory() {}
    public class CreationFactory {
       private static Object instance = null;
       public static synchronized Object createInstance() {
          if (instance == null) {
             instance = new Object();
          return instance;
      }Also I have spent several months discussing this with Peter Haggar, who believes that this code is not guaranteed to work. However I have been unable to discern from his message why he believes this will not be guaranteed to work, and I am posting this here to attempt to find a clearer explanation or confirmation that the pattern I am purposing (Double Factory) is guaranteed to work.
    Thanks,
    Scott
    ---------------------------- Original Message ----------------------------
    Subject: Re: [Fwd: Double Factory replacement for Double Check #2] From:
    "Scott Morgan" <[email protected]>
    Date: Fri, January 25, 2008 10:36 pm
    To: "Peter Haggar" <[email protected]>
    Hi Peter,
    I appologize if my last response came accross as rude or something. If
    my code is not guaranteed to work ok, can you help me understand why. I
    am after all looking for a solution for all of us.
    If my solution is wrong as you say because the member variables of the
    singleton are not up to date. I understand this to mean that the
    second_reference pointer is assigned to the memory where the instance
    object will get created before the instance object even starts the
    creation process (when the jvm allocates memory and then enters the
    constructor method of the Singleton). This doesn't seem possible to me.
    Can you refrase your statments, to help me understand your points?
    If not I am happy to turn to the original wiki for discussion.
    Thanks for your effort,
    Scott
    Thanks for asking my opinion, many times, then telling me I'm
    wrong...wonderful. You are a piece of work my friend. For what it'sworth, your email below shows you still don't understand these issues
    or what I was saying in my emails. I've been more than patient.
    >
    All the best. And by the way, your code is not guaranteed to work. It's not just me that's "wrong", it's also the engineers at Sun who
    designed Java, the JVM, and the memory model, and countless people who
    have studied it. I'm glad you have it all figured out.
    >
    Peter
    "Scott Morgan" <[email protected]>
    01/18/2008 12:47 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks I understand your position now. However am I still believe that
    it will work and be safe;
    1) the Singleton you show would be fully constructed (having exited theSingleton() method) before the createInstance() method would have
    returned.
    2) The second_reference could not be assigned until the createInstance()
    method returns.
    3) So by the time second_reference points to Singleton all of the valueswill be set.
    >
    >
    I do understand that if the createInstance method was not synchronized(at the CreationFactory class level) that my logic would be flawed, but
    since there is synchronization on that method these points are true, and
    your comments about up-to-date values are not accurate.
    >
    Cheers,
    Scott
    >In your listing from your latest email T2 does encounter a sync block
    on createInstance.
    >>>>
    No. T2 will call getInstance and see second_reference as non-null.second_reference was made non-null by T1.
    >>
    >>>>
    What are you exactly are you refering to with the phrase 'up-to-datevalues'?
    >>>>
    Assume my singleton ctor is thus:
    public class Singleton
    private int i;
    private long l;
    private String str;
    public Singleton()
    i = 5;
    l = 10;
    str = "Hello";
    T2 will get a reference to the Singleton object. However, because youaccess second_reference without synchronization it may not see i as 5,
    l as 10 and str as "Hello". It may see any of them as 0 or null. This
    is not the out of order write problem, but is a general visibility
    problem because you are accessing a variable without proper
    synchronization.
    >>
    Peter
    "Scott Morgan" <[email protected]>
    01/16/2008 11:38 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    In your listing from your latest email T2 does encounter a sync blockon createInstance.
    >>
    What are you exactly are you refering to with the phrase 'up-to-datevalues'?
    In this code the Singleton should also be
    A) non mutable (as in the instance of class Object in the example).
    If the singleton was more complex then the code to populate it'svalues
    would go inside the sync of createInstance().
    B) mutable with synchronization on it's mutator methods.
    In your article you mention out of order writes, which doesn't occurin
    this code.
    Cheers,
    Scott
    You read it wrong.
    - T1 calls getInstance which in turn calls createInstance.
    - T1 constructs the singleton in createInstance and returns to
    getInstance.
    - T1 sets second_reference to the singleton returned in getInstance. -T1 goes about its business.
    - T2 calls createInstance.
    - T2 sees second_reference as non-null and returns it
    - Since T2 accessed second_reference without sync, there is noguarantee
    that T2 will see the up-to-date values for what this object refers to.
    - Therefore the code is not guaranteed to work.
    >>>
    If this is not clear:
    - Re-read my email below
    - Re-read my article
    - If still not clear, google on Double Checked Locking and readanything
    from Brian Goetz or Bill Pugh.
    Peter
    "Scott Morgan" <[email protected]>
    01/13/2008 05:26 AM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for the reply, I don't see how T2 would see the a referenceto
    a
    partialy initialized object before the createInstance() method had
    returned. If T1 was in createInstance() when T2 entered
    getInstance(), T2 would wait on the CreationFactory's class monitor to
    wait to enter createInstance().
    Or in other words in the line of code ....
    second_reference = CreationFactory.createInstance();
    The pointer second_reference couldn't be assigned to the singleton
    instance when the synchronized createInstance() had fully constructed,initialized and returned the singleton instance. Before that the the
    second_reference pointer would always be assigned to null. So any
    thread entering getInstance() before createInstance() had returned
    (for the first time) would wait on the CreationFactory's class monitor
    and enter the createInstance() method.
    >>>
    So T2 will wait for T1.
    Cheers,
    Scott
    PS I think I am writing requirements for my next project :)
    Sorry for the delay...been in all day meetings this week.
    You are correct...I had been reading your code wrong, my apologies.
    My explanations, although correct, did not exactly correspond to your
    code.
    However, the code is still not guaranteed to work. Here's why:
    Assume T1 calls getInstance() which calls createInstance() and returnsthe
    singelton. It then sets second_reference to refer to that singleton.
    So
    far, so good. Now, T2 executes and calls getInstance(). It can see
    second_reference as non-null, so it simply returns it. But, there
    was
    no
    synchronization in T2's code path. So there's no guarantee that even
    if
    T2 sees an up-to-date value for the reference, that it will seeup-to-date
    values for anything else, ie what the object refers to...it's
    instance data. If T2 used synchronization, it would ensure that it
    read
    up-to-date
    values when it obtained the lock. Because it didn't, it could see
    stale
    values for the object's fields, which means it could see a partially
    constructed object.
    >>>>
    In the typical double-checked locking, the mistake is to assume theworst
    case is that two threads could race to initialize the object. But
    the worst case is actually far worse -- that a thread uses an object
    which
    it
    believes to be "fully baked" but which is in fact not.
    Peter
    "Scott Morgan" <[email protected]>
    01/03/2008 06:33 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for responding, I am still thinking that your mis
    interpreting
    the code so I have rewritten it here (Replacing
    DoubleFactory.instance with DoubleFactory.second_reference for
    clarity). If the T1 burps (gets interrupted) in the createInstance
    method it wouldn't have returned so the second_reference pointer
    would have never been
    assigned
    so T2 would just try again upon entering the getInstance method. Orif
    it had already entered getInstance it would be waiting to enter
    (until T1 releases the lock on CreationFactory.class ) on the
    createInstance method.
    >>>>
    public class DoubleFactory {
    private static Object second_reference = null;
    public static Object getInstance() {
    Object toRet = second_reference;
    if (toRet == null) {
    second_reference =
    CreationFactory.createInstance();
    toRet = second_reference;
    return toRet;
    private DoubleFactory() {}
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized Object createInstance() {
    if (instance == null) {
    instance = new Object();
    return instance;
    Does this clear up my idea at all?
    second_reference should be always pointing to
    null
    or
    a fully initialized Object
    (also referenced by the pointer named 'instance' ), I don't see howit would end up partially initialized.
    >>>>
    Thanks Again,
    Scott
    "It" refers to T2.
    Your createInstance method is identical to my Listing 2 and is fine
    and
    will work.
    Yes, the problem with your code is in getInstance.
    >I don't see how the DoubleFactory getInstance method could bereturning
    a partially initialized object at this point. If CreationFactoryalways
    returns a fully initialized object and DoubleFactory only assigns a
    new
    reference/pointer to it how could DoubleFactory getInstance return a
    reference/pointer to partially initialized object?
    >>>>>>>
    >>>>>
    The reason it is not guaranteed to work is explained in my previousemails
    and in detail in the article. However, I'll try again. Anytime you
    access shared variables from multiple threads without proper
    synchronization, your code is not guaranteed to work. Threads are
    allowed
    to keep private working memory separate from main memory. There are
    2
    distinct points where private working memory is reconciled with main
    memory:
    - When using a synchronized method or block - on acquisition of thelock
    and when it is released.
    - If the variable is declared volatile - on each read or write of
    that
    volatile variable. (Note, this was broken in pre 1.5 JVMs which isthe
    reason for the caveat I previously mentioned)
    Your createInstance method uses synchronization, therefore, the
    reconciliation happens on lock acquisition and lock release. T1 can
    acquire the lock in createInstance, make some updates (ie create an
    object, run it's ctor etc), but then get interrupted before exiting
    createInstance and therefore before releasing the lock. Therefore,
    T1
    has
    not released the lock and reconciled its private working memory withmain
    memory. Therefore, you have ZERO guarantee about the state of mainmemory
    from another threads perspective. Now, T2 comes along and accesses
    "instance" from main memory in your getInstance method. What will
    T2
    see?
    Since it is not properly synchronized, you cannot guarantee that T2sees
    the values that T1 is working with since T1 may not have completely
    flushed its private working memory back to main memory. Maybe it
    did completely flush it, maybe it didn't. Since T1 still hold the
    lock,
    you
    cannot guarantee what has transpired. Maybe your JVM is not usingprivate
    working memory. However, maybe the JVM your code runs on does or
    will
    some day.
    Bottom line: Your code is not properly synchronized and is notguaranteed
    to work. I hope this helps.
    Peter
    "Scott Morgan" <[email protected]>
    01/03/2008 12:49 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for your response, I don't follow what 'it' refers to in
    the
    phrase 'It can see'. So for the same reason that you state that
    example 2 from your article I believe this class CreationFactory to
    work flawlessly when a client object calls the createInstance
    method.
    >>>>>
    I see this CreationFactory code as identical to your example 2 doyou agree with this?
    >>>>>
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized Object createInstance() {
    if (instance == null) {
    instance = new Object();
    return instance;
    }Then my rational in the DoubleFactory class is that it can obtain a
    reference/pointer to the fully initialized object returned bycalling the above code. I believe you think that the problem with
    my code is
    in
    the DoubleFactorys getInstance method, is this correct?
    I don't see how the DoubleFactory getInstance method could bereturning
    a partially initialized object at this point. If CreationFactory
    always
    returns a fully initialized object and DoubleFactory only assigns a
    new
    reference/pointer to it how could DoubleFactory getInstance return a
    reference/pointer to partially initialized object?
    >>>>>
    Thanks again,
    Scott
    public static synchronized Singleton getInstance() //0
    if (instance == null) //1
    instance = new Singleton(); //2
    return instance; //3
    This above code is fine and will work flawlessly.
    Annotating my paragraph:
    T1 calls getInstance() and obtains the class lock at //0. T1 "sees"
    instance as null at //1 and therefore executes: instance = new
    Singleton() at //2. Now, instance = new Singleton() is made up of
    several lines of non-atomic code. Therefore, T1 could be
    interrupted
    after Singleton is created but before Singleton's ctor isrun...somewhere
    before all of //2 completes. T1 could also be interrupted after
    //2 completes, but before exiting the method at //3. Since T1 has
    not
    exited
    its synchronized block it has not flushed its cache. Now assume T2
    then
    calls getInstance().
    All still true to this point. However, with your code the nextparagraph
    is possible, with the code above, it's not. The reason is that T2
    would
    never enter getInstance() above at //0 because T1 holds the lock. T2will
    block until T1 exits and flushes it's cache. Therefore, the code
    above
    is
    properly thread safe.
    It can "see" instance to be non-null and thus
    return it. It will return a valid object, but one in which its ctor
    has
    not yet run or an object whose
    values have not all been fully flushed since T1 has not exited itssync
    block.
    "Scott Morgan" <[email protected]>
    01/02/2008 06:10 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for the response I understand the rational for inventing
    the
    double check anti pattern, I am sorry I still don't understand the
    difference between your solution #2 and my CreationFactory class.
    >>>>>>
    From your article figure 2.public static synchronized Singleton getInstance() //0
    if (instance == null) //1
    instance = new Singleton(); //2
    return instance; //3
    If I understand your email correctly this figure 2 is also flawed,since...
    >>>>>>
    T1 calls getInstance() and obtains the class lock at //0. T1 "sees"
    instance as null at //1 and therefore executes: instance = new
    Singleton() at //2. Now, instance = new Singleton() is made up ofseveral lines of non-atomic code. Therefore, T1 could be
    interrupted
    after Singleton is created but before Singleton's ctor isrun...somewhere
    before all of //2 completes. T1 could also be interrupted after
    //2 completes, but before exiting the method at //3. Since T1 has
    not
    exited
    its synchronized block it has not flushed its cache. Now assume T2
    then
    calls getInstance(). It can "see" instance to be non-null and thus
    return it. It will return a valid object, but one in which its
    ctor
    has
    not yet run or an object whose
    values have not all been fully flushed since T1 has not exited itssync
    block.
    So is #2 is also flawed for this reason?
    If so please revise your article, since I interpreted #2 as a
    plausible
    solution recommended by you (which lead me to the DoubleFactory
    idea).
    If not please help me understand the difference between #2 and my
    CreationFactory class.
    >>>>>>
    Thanks,
    Scott
    #2 is in Listing 2 in the article. What I meant was to forget the
    DCL
    idiom, and just synchronize the method...that's what listing 2
    shows.
    DCL
    was invented to attempt to get rid of the synchronization for 99.9%
    of
    the
    accesses.
    The solution I outlined in my email is using the DCL idiom, but on
    a
    1.5
    or later JVM and using volatile.
    You solution is not guaranteed to work. Here's why:
    public class DoubleFactory {
    private static Object instance = null;
    public static Object getInstance() {
    Object toRet = instance;
    if (toRet == null) {
    instance =
    CreationFactory.createInstance();
    toRet = instance;
    return toRet;
    private DoubleFactory() {}
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized ObjectcreateInstance()
    //1
    if (instance == null) {
    instance = new Object(); //2
    return instance;
    } //3
    }T1 calls createInstance() and obtains the class lock at //1. T1"sees"
    instance as null and therefore executes: instance = new Object() at//2.
    Now, instance = new Object() is made up of several lines of
    non-atomic
    code. Therefore, T1 could be interrupted after Object is created
    but
    before Object's ctor is run...somewhere before all of //2
    completes.
    T1
    could also be interrupted after //2 completes, but before exiting
    the
    method at //3. Since T1 has not exited its synchronized block ithas
    not
    flushed its cache. Now assume T2 then calls getInstance(). It can"see"
    instance to be non-null and thus return it. It will return a
    valid object, but one in which its ctor has not yet run or an
    object
    whose
    values have not all been fully flushed since T1 has not exited itssync
    block.
    The bottom line is that if you are accessing shared variables
    between
    multiple threads without proper protection, you are open for aproblem.
    Proper protection is defined as: proper synchronization pre 1.5,
    and
    proper synchronization or proper use of volatile 1.5 or after.
    Therefore, if you must use the DCL idiom you have one option: -
    Use DCL with volatile on a 1.5 or later JVM.
    >>>>>>>
    You can also forget about DCL and just use synchronization (listing2
    in
    my article) or use a static field (listing 10 in my article).
    I hope this clears it up.
    Peter
    "Scott Morgan" <[email protected]>
    01/02/2008 04:00 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    Re: [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    I apologies for not understanding but I don't see what is
    different
    between the solution you purposed...
    2) Don't use DCL but use synchronization
    and the code that I am putting forward. Perhaps I do just notunderstand
    but you seem to be contradicting yourself in this email?
    I understand that you are saying in #2 that this will always 'work'
    with
    out any issues...
    public static Object instance = null;
    public static synchronized Object getInstance() {
    if (instance == null) {
    instance = new Object();
    return instance;
    But first you seem to say in the email that if T1 gets
    interrupted
    it
    may leave the instance pointing to a partially initialized object?
    So as far as I understand it the createInstance method in my
    CreationFactory class should be successful (always retuning a
    fully initialized object) for the same reason #2 is successful.
    Please keep in mind that there are two different instancepointers
    in
    the code I sent you, one is part of the DoubleFactory class and
    the other is part of the CreationFactory class.
    >>>>>>>
    Thanks for your time, just looking for better solutions!
    Scott
    Scott,
    Your solution is not guaranteed to work for various reasons
    outlined
    in
    the article. For example, you can still return from your code apartially
    initialized object. This can occur if T1 gets interrupted beforeleaving
    the synchronized method createInstance() and T2 calls
    getInstance().
    T2
    can "see" toRet/instance as non-null but partially initialized
    since
    T1
    has not fully flushed its values.
    As of 1.5, Sun fixed various issues with the memory model that
    were
    broken. Double Checked Locking will still break unless you usevolatile
    (which was fixed in 1.5). Therefore, the following code works:
    volatile Helper helper;
    Helper getHelper() {
    if (helper == null)
    synchronized(this) {
    if (helper == null)
    helper = new Helper();
    return helper;
    but the original DCL idiom will not work. So, your options are:
    1) Use DCL with volatile (above)
    2) Don't use DCL but use synchronization
    3) Don't use DCL, but use a static field.
    #2 and #3 are outlined in my article from 2002.
    Hope this helps,
    Peter
    "Scott Morgan" <[email protected]>
    12/26/2007 04:12 PM
    Please respond to
    [email protected]
    To
    Peter Haggar/Raleigh/IBM@IBMUS
    cc
    Subject
    [Fwd: Double Factory replacement for Double Check #2]
    Hi Peter,
    Thanks for the article on the out of order write problem. Whatdo
    you
    think of this as a solution?
    TIA,
    Scott
    ---------------------------- Original Message----------------------------
    Subject: Double Factory replacement for Double Check #2
    From: "Scott Morgan" <[email protected]>
    Date: Wed, December 26, 2007 2:55 pm
    To: [email protected]
    Hi Ward,
    Here is a pattern submission
    Double Factory
    Lazy initialization of singletons in accepted for a while usingthe
    double check pattern. However it has been discovered that the
    double
    check pattern isn't thread safe because of the out of order write
    problem. This problem occurs when Threads entering the Singleton
    Factory method return with a fully constructed, but partially
    initialized, Singleton object.
    >>>>>>>>
    Therefore: It makes sense to look for a way to initializeSingletons
    in
    a Lazy and Thread Safe manor. The following illustrates a fairly
    simple
    solution...
    package foo;
    public class DoubleFactory {
    private static Object instance = null;
    public static Object getInstance() {
    Object toRet = instance;
    if (toRet == null) {
    instance =
    CreationFactory.createInstance();
    toRet = instance;
    return toRet;
    private DoubleFactory() {}
    public class CreationFactory {
    private static Object instance = null;
    public static synchronized ObjectcreateInstance()
    if (instance == null) {
    instance = new Object();
    return instance;
    This gets around the out of order write problem because all
    Threads
    waiting on the CreationFactory's Class monitor will have a fully
    constructed and initialized instance when they actually exit the
    createInstance method.
    >>>>>>>>
    >>>>>>>>
    During runtime while the Singleton instance is getting created(constructed and initialized) there may be a few Threads waiting
    on
    the
    CreationFactory Class's objects monitor. After that period all
    the
    Treads
    accessing
    the Singleton will have unsynchronized reads to the instance,
    which
    will
    optimize execution.
    References:
    http://www.ibm.com/developerworks/java/library/j-dcl.html
    Copyright 2007 Adligo Inc.

    Scott-Morgan wrote:
    Hi All,
    Thanks for your comments, here are some more....
    jtahlborn you state that
    the only way to guarantee that a (non-final) reference assignment is visible across threads is through the use of volatile and synchronized,
    From the jvm spec
    http://java.sun.com/docs/books/jls/third_edition/html/memory.html
    17.4.1 Shared Variables
    Memory that can be shared between threads is called shared memory or heap memory.
    All instance fields, static fields and array elements are stored in heap memory.
    Since both the second_reference and instance fields are both static, they are shared and visible across all threads.Yes, all these things are shared across threads, however, if you keep reading, there is a notion of "correct" sharing. obviously these values may be visible, that's why double-checked locking was used for so long before people realized it was broken. it worked most of the time, except when it didn't, and that's what i'm trying to show. that the only way to correctly share state between threads is via synchronization points, the most common being volatile and synchronized (there are a couple of other less used ones which don't apply here). The articles you linked to below from ibm cover the "visibility" in great depth, this is exactly what i am referring to.
    You also state that volatile is a solution, but you seem to rebut your self in stating that the overhead for volatile is almost as great as synchronization.
    This article illustrates the solution, and also comments on the overhead of volatile.
    http://www.ibm.com/developerworks/library/j-jtp03304/
    linked from
    http://www.ibm.com/developerworks/java/library/j-dcl.html
    volatile is a solution, in that it is correct, and you avoid the appearance of synchronization each time. however, since the semantics of volatile were strengthened in the new memory model, using volatile will perform practically (if not exactly) the same as simply synchronizing each time. the article you link to says exactly this under the heading "Does this fix the double-checked locking problem?".
    Also could you be more specific about the example at the end of the jvm memory spec page, like a section number?It's the very last thing on the page, the "discussion" under 17.9, where it mentions that changes to "this.done" made by other threads may never be visible to the current thread.

  • Trying to understand factory pattern - having some problems

    hi,
    I am tryin to learn the implementation of Factory design pattern and I came across this link after searching this forums:
    http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
    My question is:
    In the example they have different DAOFactories that have the database specific details like:
    // Cloudscape concrete DAO Factory implementation
    import java.sql.*;
    public class CloudscapeDAOFactory extends DAOFactory {
      public static final String DRIVER=
        "COM.cloudscape.core.RmiJdbcDriver";
      public static final String DBURL=
        "jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";
      // method to create Cloudscape connections
      public static Connection createConnection() {
        // Use DRIVER and DBURL to create a connection
        // Recommend connection pool implementation/usage
      public CustomerDAO getCustomerDAO() {
        // CloudscapeCustomerDAO implements CustomerDAO
        return new CloudscapeCustomerDAO();
      public AccountDAO getAccountDAO() {
        // CloudscapeAccountDAO implements AccountDAO
        return new CloudscapeAccountDAO();
      public OrderDAO getOrderDAO() {
        // CloudscapeOrderDAO implements OrderDAO
        return new CloudscapeOrderDAO();
    }But in my application I have stored all the database specific information in the server.xml of my tomcat server.So,how can I read different database configuration information for different databases like Oracle,Cloudbase,MySQL etc ????
    Please help.

    Thanks duffmo,
    But atleast provide some link then that shows wats inHere's two:
    http://www.springframework.org
    http://www-128.ibm.com/developerworks/java/library/j-dao/
    Personally, I don't worry about DAO factory classes.
    If I have a class Foo that I want to persist I'll have a companion DAO interface that will look like this:
    public interface FooDao
        public Foo find(long id);
        public List<Foo> findAll();
        public void saveOrUpdate(Foo foo);
        public void delete(Foo foo);
    }There are more finders if I have other candidate keys.
    I want to have all the datasource information out of
    my code in server.xml,context .xml or some other xml
    file from which my java code should read the
    information,so which is the ideal way to do if you
    want to make your application generic in the sense it
    can be used with any database.Yes, I agree. Your database stuff will be in the Spring context and your app server's JNDI data source.
    %

Maybe you are looking for

  • PI 711 Installation: Loading of 'SAPNTAB' import package: error but no log

    Hello, I'm perfromong an installation of a SAP PI 7.11 ystem on windoows Server 2003 and Oracle 10.2 . I've perfromed the installation of the DEV system without particular issue. But now when tryning to install the QAS system , I can't finish the ins

  • What the heck am I doing wrong???

    The error message I'm getting is the following: "week4_herbie must be defined in its own file" The problem that I'm running into is that the programs are supposed to work together. One (week4_herbie) handles the mortgage calculation itself (and set u

  • Contacts do not display on iphone4 phone calls

    I recently migrated data from a blackberry to an iphone 4. when I get a call from a known contact, the display says unknown caller. Any suggestions?

  • Photoshop Suddenly Stopped Opening Files

    Suddenly Photoshop CC will not open any files. I was in the middle of processing photos, finished one up, saved it and tried to open a new file... and nothing. No error message. When I try to open a file, Photoshop lets me browse to the file and clic

  • IPhoto '11 Crashes when selecting External Editor in Advanced Prefs

    When I select "In Adobe Photoshop CS5..." in the dropdown shown below, iPhoto immediatly crashes. Any suggestions? I am using iPhoto '11 9.4.2 & Photoshop CS5 12.0.4 on a MacBook Pro running Lion 10.7.5. I submitted a crash report to Apple. I would i