Lazy Initialization

Josh Bloch and Neal Gafter posted the following code puzzler. The thread in the static block blocks if you do "t.join()" but "t.join(10)" lets the program finish. Is this due to the private static variable which is being lazily initialized? Thanks for any mind-opening explanations!
public class Lazy {
private static boolean initialized = false;
static {
Thread t = new Thread(new Runnable() {
public void run() {
initialized = true;
t. start();
try {
t.join();
} catch (InterruptedException e) {
throw new AssertionError(e);
public static void main(String[] args) {
System.out.println(initialized);
}

o, when the thread tries to update the value of
the 'initialized' variable, it cannot because the
lock for the Class object is held by a different
Thread.
But.... the Thread is NOT synchronized, so why should
it care about locks? It's a sort of class
initialization magic, right?The section in the JVM spec just before the link I provided states:
=============
A class or interface type T will be initialized immediately before one of the following occurs:
* T is a class and an instance of T is created.
* T is a class and a static method of T is invoked.
* A nonconstant static field of T is used or assigned.
=============
Note the last item.
Since the static initializer has not exited, the Class has not been initialized, therefore , the attempt to assign a value to 'initialized' in the Thread attepts to initialize the class (again) but finds it locked and the lock will never be released due to the join().
When join(10) is used, the static block exits, and releases the lock. On release of the lock, any waiting threads are notified, and from the spec:
=============
If the class or interface has already been initialized, then no further action is required. Release the lock on the Class object and complete normally
=============
So, the second attempt to initialize the class (in the thread) finds the class already initialized, and therefore the initialization simply releases the lock and ends.
Jim S.

Similar Messages

  • Lazy Initialization Exceptions

    Our Java naturally classes contain properties which are
    relationships to other classes - either one to many or many to one.
    Due to the fact that these relationships are so intertwined, many
    given objects end up referencing a large portion of the database if
    one were to recursively follow all of the nested relationships. As
    such, we desire to have the option of not loading certain
    relationships when the data is not needed.
    We use EJB 3.0 (JBoss implementation using Hibernate) for
    object persistence. It allows the option of uninitialized
    collections and other referenced objects.
    The Flex process of serialization to AMF causes serious
    problems for this design. It tries to touch all of these properties
    while building the binary representation for sending over the wire.
    This triggers an immediate attempt to initialize the objects which
    are still in the uninitialized state.
    This causes the LazyInitializationException to be thrown by
    the O/R framework - because the transaction is already closed
    (which effectively means the call to the DAO has returned).
    The community only offers two suggestions, both which do not
    work with Flex (or Flash Remoting for that matter). T
    he first is simply initializing everything ahead of time.
    This does not work because eventually you have to draw the line
    somewhere, and the Flex serialization routines will find that line
    and try to cross it.
    The second is the open session in view pattern, meaning that
    we open the transaction as soon as the Flex client makes a request,
    and close it only when the last response has been made. This does
    not work either, because Flex would end up initializing everything
    during serialization.
    I have gone to the extent to writing a custom aspect to
    intercept returning calls from my DAO and null out the Hibernate
    proxies. This worked until I tried to use it for uninitialized many
    to one relationships. Nulling them out actually deletes my
    relationship in the database!
    The only solution I see is to add intelligence to the Flex
    serialization techniques which watch for this scenario, and avoid
    triggering the lazy initialization.
    Any suggestions would be appreciated.

    quote:
    Originally posted by:
    busitech
    Our Java naturally classes contain properties which are
    relationships to other classes - either one to many or many to one.
    Due to the fact that these relationships are so intertwined, many
    given objects end up referencing a large portion of the database if
    one were to recursively follow all of the nested relationships. As
    such, we desire to have the option of not loading certain
    relationships when the data is not needed.
    We use EJB 3.0 (JBoss implementation using Hibernate) for
    object persistence. It allows the option of uninitialized
    collections and other referenced objects.
    The Flex process of serialization to AMF causes serious
    problems for this design. It tries to touch all of these properties
    while building the binary representation for sending over the wire.
    This triggers an immediate attempt to initialize the objects which
    are still in the uninitialized state.
    This causes the LazyInitializationException to be thrown by
    the O/R framework - because the transaction is already closed
    (which effectively means the call to the DAO has returned).
    The community only offers two suggestions, both which do not
    work with Flex (or Flash Remoting for that matter). T
    he first is simply initializing everything ahead of time.
    This does not work because eventually you have to draw the line
    somewhere, and the Flex serialization routines will find that line
    and try to cross it.
    The second is the open session in view pattern, meaning that
    we open the transaction as soon as the Flex client makes a request,
    and close it only when the last response has been made. This does
    not work either, because Flex would end up initializing everything
    during serialization.
    I have gone to the extent to writing a custom aspect to
    intercept returning calls from my DAO and null out the Hibernate
    proxies. This worked until I tried to use it for uninitialized many
    to one relationships. Nulling them out actually deletes my
    relationship in the database!
    The only solution I see is to add intelligence to the Flex
    serialization techniques which watch for this scenario, and avoid
    triggering the lazy initialization.
    Any suggestions would be appreciated.

  • Problem with lazy initialization in inhereted class

    Hi. I have a strange problem. I have 2 classes CMRCommandInputPanel (view ) , class CommandInputFieldsModel (view's model) and 2 classes that inherets from them: CMRDerivitiveCommandInputPanel and DerivativeCommandInputFieldsModel.
    the Views looks like:
    public class FormPanel extends JPanel {
        protected AbstractFormDataModel mFormModel = null;
        public FormPanel(AbstractFormDataModel formModel) {
            super();
            initialize(formModel);
        private void initialize(AbstractFormDataModel formModel) {
            mFormModel = formModel;
    public class CMRCommandInputPanel extends FormPanel {
         public CMRCommandInputPanel(AbstractFormDataModel formModel) {
              super(formModel);
              initialize();
         private void initialize() {
              initLocalModels();
            JPanel mainPanel =  new JPanel () ;
             mainPanel.setLayout(new BorderLayout());
            mainPanel.add(getUpperButtonsPanel(), BorderLayout.NORTH);
            mainPanel.add(getFormPanel(), BorderLayout.CENTER);
            mainPanel.add(getDownButtonsPanelDefault(), BorderLayout.SOUTH);
            mainPanel.addMouseListener(new MouseAdapter(){
                public void mouseClicked(MouseEvent e) {
                     // set focus on the formPanel in order to set the entered value on mouse click.
                        getFormPanel().requestFocus();
            this.setLayout(new BorderLayout());
            this.add(mainPanel);
            this.setBorder(UIConstants.DEFAULT_PANEL_BORDER);
         protected CMRPanel getFormPanel() {
              if (mFormPanel == null) {
                    adding editable TextFields to the panel.
             return mFormPanel;
         protected void initLocalModels(){
              new CommandInputFieldsModel(mFormModel,this);
    public class CMRDerivitiveCommandInputPanel extends CMRCommandInputPanel {
         private JTitledTextField mRealizationPriceField = null;
         public CMRDerivitiveCommandInputPanel(AbstractFormDataModel formModel) {
              super(formModel);
    // override of  super method
         protected CMRPanel getFormPanel() {
              if (mFormPanel == null) {
                    adding super classes  editable TextFields to the panel and some new ones
              return mFormPanel;
         /* (non-Javadoc)
          * @see cmr.client.ui.CMRCommandInputPanel#initLocalModels()
         protected void initLocalModels() {
              new DerivativeCommandInputFieldsModel(mFormModel,this);
         public JTextField getRealizationDateField() {
              if (mRealizationDateField == null) {
                   mRealizationDateField = new JTextField();
              return mRealizationDateField;
    public class CommandInputFieldsModel extends AbstractFieldsDataModel {
         protected CMRCommonDataModel mFormModel = null;
         protected CMRCommandInputPanel mView = null;
         public CommandInputFieldsModel(CMRCommonDataModel data,CMRCommandInputPanel aView){
              mFormModel = data;
              mView = aView;
              mFormModel.registryModel(this,ExBaseDataController.META_KEY);
              mFormModel.registryModel(this,CompanyMessagesController.META_KEY);
              mFormModel.registryModel(this,DefaultFinancialValueController.META_KEY);
              mFormModel.registryModel(this,QuantityValueController.META_KEY);
              mFormModel.registryModel(this,RateForPercentController.META_KEY);
         /* (non-Javadoc)
          * @see cmr.client.ui.data.CMRUpdatable#updateData(java.lang.Object)
         public void updateData(Object aNewData) {
                updating relevant fields by using getters of View
    public class DerivativeCommandInputFieldsModel extends CommandInputFieldsModel {
         public DerivativeCommandInputFieldsModel(CMRCommonDataModel data,CMRDerivitiveCommandInputPanel aView){
              super(data,aView);
         /* (non-Javadoc)
          * @see cmr.client.ui.data.CMRUpdatable#updateData(java.lang.Object)
         public void updateData(Object aNewData) {
              if (aNewData instanceof RealizationData){
                   RealizationData realizationData =  (RealizationData)aNewData;
                   CMRDerivitiveCommandInputPanel theView = (CMRDerivitiveCommandInputPanel)mView;
                   theView.getRealizationDateField().setValue(realizationData.getRealizationDate());
                   theView.getRealizationPriceField().setValue(realizationData.getRealizationPrice());
              }else
                   super.updateData(aNewData);
    }The problem is , that when the field's getter of inhereted view's class is called from model for updating field,the fields are beeing initialized for second time. they simply somehow are equal to NULL again. I've checked reference to the view and it's the same,but only new fields still equals to NULL from model.
    is someone can help me with that?

    The only thing that springs to mind is that you're
    exporting the newly created fields model object in
    the superclass constructor (at least I assume that's
    what the registry calls do).
    That can cause problems, especially in a
    multi-threaded environment (though it's often
    tempting). Again there's a risk that the
    partly-initialized object may be used.
    Actually this is a bit of a weakness of Java as
    opposed to C++. In C++ a new object has the virtual
    method table set to the superclass VMT during
    superclass initialisation. In Java it acquires its
    ultimate class indentity immediately.
    You'd be safer to extract all that kind of stuff from
    the superclass constructor and have some kind of
    init() method called after the object was
    constructed.
    In fact whenever you see a new whose result
    you don't do anything with, then you should take it
    as a warning.thank you for your replies. ;) I've managed to solve this matter. Simply fully redefined my panel with fields in child-class and added to it's constructor local initialization() method as well, which creates UI of child-class. Even that I initialize UI twice, but all fields are initialized with "lazy initialization" , so there is only once NEW will be called. but there is something weird going in constructors with ovverwritten methods.

  • Concurrent, non-synchronized, lazy initialization: is this correct?

    Guys, I would appreciate a sanity check on some code of mine.
    I have a class, call it State. Every instance is associated with a key of some type. Each user will know the key it wants to use. It will present that key to State to request the corresponding State instance. They must always receive back that sole instance that corresponds to key. The keys are unknown until runtime, so you must lazy initialize a State instance when first presented with a given key.
    If concurrency was not an issue, then State could have lazy initialization code like this:
         /** Contract: never contains null values. */
         private static final Map<Object,State> map = new HashMap<Object,State>();
         public static State get(Object key) {
              State state = map.get(key);
              if (state == null) {
                   state = new State();
                   map.put(key, state);
              return state;
         private State() {}     // CRITICAL: private to ensure that get is the only place instances createdBut heavy concurrency on get is present in my application. While I could trivially make the above code safe by synchronizing get, that would cause it bottleneck the entire application. Vastly superior would be the use of some sort of concurrent data structure that would only bottleneck during the relatively rare times when new State instances must be created, but would allow fast concurrent retrievals when the State instance has already been created, which is the vast majority of the time.
    I think that the unsynchronized code below does the trick:
         /** Contract: never contains null values. */
         private static final ConcurrentMap<Object,State> map = new ConcurrentHashMap<Object,State>();
         public static State get(Object key) {
              State current = map.get(key);
              if (current != null) return current;
              State candidate = new State();
              current = map.putIfAbsent(key, candidate);
              return (current == null) ? candidate : current;
         }Here is how it works: most of the time, just the first two lines
         /** (ignore this) */
         State current = map.get(key);
         if (current != null) return current;will be executed because the mapping will exist. This will be really fast, because ConcurrentHashMap is really fast (its always slower than HashMap, but maybe only 2X slower for the scenario that I will use it in; see [https://www.ibm.com/developerworks/java/library/j-benchmark2/#dsat] ).
    If the relevant State instance is not present in map, then we speculatively create it. Because get is unsynchronized, this may/may not be the one actully put on map and returned by the subsequent lines of code because another thread supplying the same key may be concurrently executing the same lines of code. That's why its named candidate.
    Next--and this is the real critical step--use ConcurrentMap's atomic putIfAbsent method to ensure that just the first thread to call the method for a given key is the one who suceeds in putting it's candidate in map. We reassign current to the result of putIfAbsent. Its value will be null only if there was no previous mapping for key but this call to putIfAbsent suceeded in putting candidate on map; thus, candidate needs to be returned in this case. But if current is not null, then some other thread with the same key must have been concurrently calling this code and was the thread which suceeded in putting its State on map; thus in this case current will have that other thread's value and so return it (with this thread's candidate being a waste; oh well).
    Note that this problem is similar in spirit to the infamous double checked locking idiom. Since that is such a treacherous minefield
    [http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html].
    I would really appreciate another set of eyes looking over my code.

    Hi Bbatman,
    Thank you so much for your answer.
    Pietblock: I believe that your double checked locking proposal is still wrong.OK, I do believe you.
    Did you read the link that I provided in my initial post?
    It discusses some known solutions,
    the best of which for singletons is a value helper class,
    followed by making the reference to your singleton be volatile
    (assuming that you are using jdk 1.5+).Yes, I did read that article some time ago, when I first got warned for double checking. I never quite understood the keyword "volatile". Now, when reading it again, I see some light glimmering.
    But your proposal has some strange elements.
    First, both the singleton field as well as accessor method are always static
    --why did you make them instance based in your code?
    In order to call them, you already need an instance which defeats the purpose!
    Are you sure about that choice?Yes, that is deliberately. The intended use is to define a static instance of SingletonReference in a class that needs to be instantiated as a singleton. That reference is then used to obtain the singleton.
    Assuming that leaving out static on those was a typo,
    the only innovation in your proposal is the claim that
    "Executing an instance method on the new singleton prevents inlining".
    Where did you get that idea from?
    Its news to me. Instance methods often get inlined, not just static methods.The non static field is not a typo, but intentional. What you call a "innovation", my assumption that I prevented inlining, is exactly what I was not very sure about. I can't imagine how an interpreter or JIT compiler would navigate around that construct, but nevertheless, I am not sure. Your remark suggests that it is unsafe and I will reconsider my code (change it).
    The reason why most double checked locking solutions fail,
    including I believe yours,
    is due to completely unintuitive behavior of optimizing java runtime compilers;
    things can happen in different time order than you expect if you do not use some sort of locking.
    Specifically, typical double checked locking fails because there is no lock on the singleton,
    which means that writes to it can occur in strange order,
    which means that your null-check on it may not prevent multiple instances from being created. Yes, you convinced me.
    Thank you so much for looking into it
    Piet

  • Lazy initialization of ValueHolderInterface

    We are initializing the value holders lazily, for example we are initializing them checking them if they are null in the getter methods, from
    the code patterns it is always seem that value holders are initialized in the constructors of the POJO. what are the problems associated
    with lazy initialization of valueholderinterface? thanks

    Should be ok, and more optimal. When TopLink generates/weaves code it initializes them lazily (since 10.1.3).
    James : http://www.eclipselink.org

  • How to lazy initialize iterators?

    Hello,
    I'm using JDeveloper 11.1.1.4.0.
    In Managed bean c'tor, I am getting the row attribute values from an iterator, Iterator1. These values are then stored in session.
    Subsequently I need to use these session values to fetch data from another iterator, say Iterator2.
    Following is the code written.
            DCIteratorBinding iterator =
                ((DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry()).findIteratorBinding(iteratorName);getCurrentBindingsEntry() calls Iterator2, tries to initialize it and does not find Iterator1 values in session. It then throws NullPointer exception.
    How do I ensure that getCurrentBindingsEntry() does NOT initializing all the iterators in the same binding?
    Regards,
    Amar

    John,
    Here is the use case:
    1. My page has a few multiSelectCheckboxes, selectOneChoice and three tables. Each of these is based on different iterators.
    2. In managed bean c'tor, multiSelectCheckboxes and selectOneChoice are to be populated. I'm fetching each of the iterator rows using the code given below.
        private ArrayList getAllIteratorValues(String iteratorName,
                                               String attributeName) {
            DCIteratorBinding iterator =
                ((DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry()).findIteratorBinding(iteratorName);
            ArrayList attributeValues = new ArrayList();
            for (int i = 0; i < iterator.getEstimatedRowCount(); i++) {
                Row row = iterator.getRowAtRangeIndex(i);
                Object attribute = "";
                attribute = row.getAttribute(attributeName);
                attributeValues.add(attribute);
            return attributeValues;
        }3. The populated values are stored in session. I'm required to do this as the same values are required on some other pages as well.
    4. Table iterators are to be executed using session values.
    While executing step 2 above, when it calls BindingContext.getCurrent().getCurrentBindingsEntry(), it executes the VOImpl for one of the tables. In this VOImpl, it looks for the session values and throws NullPointerException.
    So is there any way to populate only one iterator at a time (the ones for selectOneChoice/multipleCheckBox) and not all the iterators in 'bindings'?
    Amar

  • Passing initialization parameters to a singleton

    So here's the classic Singleton code:
    public class MySingleton {
    private static MySingleton _instance;
    private MySingleton() {
    // construct object . . .
    public static synchronized MySingleton getInstance() {
    if (_instance==null) {
    _instance = new MySingleton();
    return _instance;
    What I can't find any discussion of is: what do you do if that "// construct object . . ." bit requires parameters (e.g. the username and password for the DB connection)?
    Obviously, adding those parameters to the getInstance() method would be a bad idea so some kind of init() method is probably required. I've used that approach in simple cases so the calling sequence is
    MySingleton foo = MySingleton.getInstance();
    foo.init(parameterObject);
    That's fine so long as the initialization is simple and I can keep track of where the singleton gets used and just be careful not to use it before init() gets called. But if the initialization involves setting up a DB connection, how do I arrange the code so (a) most of my application can just call getInstance() without worrying about error situations (b) the code that does set up the connection can do so reliably and provide detailed analysis when something does go wrong and (c) the app doesn't just crash when some other idiot calls getInstance() without first calling init(), or calls init() multiple times with different parameters? Or does that last possibility mess up the singleton so badly I should reject the init() idea and take a different approach entirely?
    Thanks,
    Graeme

    Hi Graeme! I guess I misunderstood what you wanted to do. I was under the impression that the necessary data (eg. DB connection parms) was not dependent upon user input.
    Based on what you've described, are you sure you need a singleton? Here's a possible implementation. If there are items that are constant (for the most part anyway) such as database names, connection strings, etc., those can be located in a properties file which is read once, when the singleton instance is created. Now, let's say one of the variables is a user id & password, which are supplied by a given user. Then, your implementation could look somewhat like the following:
    public class DBAccess
       private static DBAccess m_instance;
       private DBAccess()
          // Read properties file and store necessary data
       public static DBAccess getInstance()
          // Standard lazy initialization here
       public DBConnection getConnection( String userId, String password )
          // Get actual DB connection using the supplied arguments
       // Any other required methods
    } // class DBAccessNote that the getConnection() method above is an instance method, not a class method.
    The above code presents a single, well-known point of access to a database. You can add any other instance methods you deem necessary. Note that some instance methods may need to be declared with the synchronized keyword, based upon the data it handles to avoid concurrency problems.
    Hope this helps!
    Cheers!
    -- Amol.

  • Lazy loading differences Toplink vs. Hibernate - plz. explain

    I'm in the process of evaluating both Toplink and hibernate as potential ORM framework to use for a project I'm currently involved in.
    My question is about how Toplink resolves lazily loaded associations. In hibernate I have to perform a query inside a transactional context boundary, like:
    Session s = SessionFactory.getSession();
    s.beginTransaction();
    ... your query logic here
    s.getTransaction().commit();When the query involves associations which are declared as lazily loadable, trying to invoke these associations after the transaction boundary has been closed, results in an exception. This differs from Toplink (my JUnit testcase breaks for Hibernate if I set the DAOFactory to return hibernate enabled DAO's) and I'm wondering why?
    I'm guessing this has something to do with how Toplink manages its clientsession, but would like to get some confirmation about this. It looks like as-long as the thread of execution is running I can resolve associations using Toplink, but not when I use Hibernate.
    This brings me to yet another question - what's considered best practices in Toplink regarding session disposal. Should I do something myself, or let the garbage collector take care of it?

    I'm not too sure here, but I think it's because TopLink has a "long running" ServerSession. When you do lazy initialization outside a clientsession it is for read only purposes and it will use the centrally managed ServerSession (and cache). I'm still trying to figure out the exact relationships here, som I'm not too sure. :) Hibernate does not have a centrally shared cache, and will not be able to instantiate objects if the session is closed (for each session, objects are instantiated from it's data cache).
    As for handling resources and closing/opening, use the Spring/TopLink integration. It will handle it for you and give you heaps of convenience methods that uses some clever tricks to decide if it should fetch objects with Session or UnitOfWork. It will also do some good Exception handling built into Spring.

  • JSF and Hibernate Lazy loading

    Hello,
    It seems like Hibernate session is being closed after exception. This makes a conflict with JSF, since after session is closed lazy initialization cannot take place and the view of the page cannot be rendered.
    Is it right that Hibernate session is closed after exception ?
    How can this problem be treated ?

    Thanks,
    The problem happened since I was making rollback right after the exception. The session is closed after a rollback ...
    I am already using session-per-request (my own implementation). I changed the code to make rollback only once at the end of the filter. If a caught exception happens during request I only register a request for rollback.

  • Remote client, Lazy relationship and Serialization

    hi,
    I know that all the things mentioned in the subject were discussed here and not once, but forgive me and let me clarify it once again.
    Suppose my entity A has 1-m (lazy) relationship to another entity B.
    Is it true that it won't be enough to FETCH JOIN entity B together with entity A prior to Serialization to the client JVM, like:
    ReadObjectQuery query = new ReadObjectQuery(A.class);
    query.addJoinedAttribute(query.getExpressionBuilder().getAllowingNull("b"));
    I MUST explicitly access this relationship PRIOR to Serialization to the client JVM, otherwise LAZY initialization exception will be thrown at client side.
    Using: TopLink - 11g Technology Preview 3 (11.1.1.0.0) (Build 071214)
    regards,

    sorry!
    I have missed one point from the documntation ...
    I was doing the query directly on the UnitOfWork and accordingly to the documentation "it clones only the mapped attributes of registered objects, and stops at indirection objects unless you trigger the indirection".
    Using ClientSession resolves the problem!
    cheers,

  • Internal Frames problem

    Hi,
    I am writing a piece of code where I want to able to choose from a menu a screen that displays multiple graphs (using Internal frames.) I am using cardlayout to bring up the various options I choose from the menu. I have simplified my program as much as possible but I still seem to be getting the same error
    Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container .......
    I know I shouldn't be adding a window to a container but I can't see how I can change my code so it has the functionality I desire.
    Here is the code I am using
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JFrame
         public Test()
             JPanel card1 = new JPanel();
             card1.add(new InternalFrameDemo());
              getContentPane().add(card1);
        public static void main(String[] args)
              Test frame = new Test();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(200, 200);
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class InternalFrameDemo extends JFrame
        JDesktopPane desktop;
        static final int xOffset = 30, yOffset = 30;
        private JLabel graph1;
        private String Graph1;
        public InternalFrameDemo() {
            super("InternalFrameDemo");
            //Make the big window be indented 50 pixels from each edge
            //of the screen.
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            //Set up the GUI.
            desktop = new JDesktopPane(); //a specialized layered pane
            createFrame(); //create first "window"
            setContentPane(desktop);
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        //Create a new internal frame.
        protected void createFrame() {
            MyInternalFrame frame = new MyInternalFrame();
            frame.setVisible(true);
            desktop.add(frame);
            try {
                frame.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
        //Quit the application.
        protected void quit() {
            System.exit(0);
       public void MyInternalFrame() {
         System.out.println("graph1");
         graph1 = new JLabel("", 
                       new ImageIcon("../images/Graph1.jpg"),
                       JLabel.CENTER);
         getContentPane().add(graph1);
         //...Then set the window size or call pack...
         setSize(500,550);
    }If anyone could point me in the right direction it would be great. Thanks in advance!

    But I actually do not understand what that card layout thing is all about. If you want to hide/show internal frames you can simply use setVisible() and setSelected() like examplified below (I did put all code in the same file for my convenince). I have put a text in the label so that you can see that it is replaced. Using aJLabel to show an image is however a little bit weird.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    class MyInternalFrame extends JInternalFrame
      private JLabel graph1;
      public MyInternalFrame(String text)
        graph1 = new JLabel(text, 
                            new ImageIcon("../images/Graph1.jpg"),
                            JLabel.CENTER);
        getContentPane().add(graph1);
        setSize(500,550);
    public class InternalFrameDemo extends JFrame
      private JDesktopPane desktop;
      private final MyInternalFrame[] frames;
      public InternalFrameDemo()
        super("InternalFrameDemo");
        frames = new MyInternalFrame[3];
        //Make the big window be indented 50 pixels from each edge of the screen.
        int inset = 50;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(inset, inset,
                  screenSize.width  - inset*2,
                  screenSize.height - inset*2);
        //Set up the GUI.
        desktop = new JDesktopPane(); //a specialized layered pane
        setContentPane(desktop);
        frames[0] = createFrame("Hello world!");
        frames[1] = createFrame("Hello again, world!");
        frames[2] = createFrame("Goodbye cruel world!");
        desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        setSize(500, 500);
        Thread animThread = new Thread()
            public void run()
              for (int i = 0; i < frames.length; ++i)
                final int frameId = i;
                SwingUtilities.invokeLater(new Runnable()
                    public void run()
                      // Hide frame that is showing.
                      if (frameId != 0)
                        frames[frameId - 1].setVisible(false);
                      System.out.println("Replacing image: " + frameId);
                      frames[frameId].setVisible(true);
                      try
                        frames[frameId].setSelected(true);
                      catch (java.beans.PropertyVetoException exc)
                        exc.printStackTrace();
                try
                  Thread.sleep(3000);
                catch (InterruptedException exc)
                  exc.printStackTrace();
        animThread.start();
      //Create a new internal frame.
      protected MyInternalFrame createFrame(String text)
        MyInternalFrame frame = new MyInternalFrame(text);
        desktop.add(frame);
        return frame;
      public static void main(String[] args)
        JFrame frame = new InternalFrameDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }Using lazy initialization where you postpone the creation of an internal frame until it is actually shown would be an improvement.
    The setVisible/Selected() call can of course be triggered by something else in your application.
    Note that changes of swing components shall be made in the EDT.

  • Auto-generated Swing Code: jbInit()

    Hi,
    I noticed that the auto-generated code for Swing apps directly uses class member variables, which is far from ideal. For example:
    public class Screen {
        private JLabel boardingPassLabel = new JLabel();
        public void jbInit() {
            boardingPassLabel.setText("Boarding Pass");
            boardingPassLabel.setBounds(new Rectangle(170, 25, 115, 20));
            boardingPassLabel.setFont(new Font("Tahoma", 1, 12));
    }The issue is that instantiating Screen will cause a JLabel to also be instantiated. While this is fine for a single screen and a single label, if there are hundreds of screens, each with twenty labels and buttons, it quickly gets out of hand.
    It would be nice to see the following code auto-generated:
    public class Screen {
        private JLabel boardingPassLabel;
        public void jbInit() {
            JLabel boardingPassLabel = getBoardingPassLabel();
            boardingPassLabel.setText("Boarding Pass");
            boardingPassLabel.setBounds(new Rectangle(170, 25, 115, 20));
            boardingPassLabel.setFont(new Font("Tahoma", 1, 12));
        public JLabel getBoardingPassLabel() {
          if( boardingPassLabel == null ) {
            boardingPassLabel = createBoardingPassLabel();
          return boardingPassLabel;
        protected JLabel createBoardingPassLabel() {
          return new JLabel();
    }This allows subclasses to provide a different subclass of JLabel (if needed). It also means that there is little overhead to instantiating the Screen class. Thus if we had to instantiate 100 screens, each with 20+ widgets, there would be no performance hit.
    As a work-around, we can simply not instantiate the Screen classes until just before they are used. This may not work in our situation, though.
    Thoughts?
    D

    I should probably add a detail here.
    We are running the Swing app on the CrEme JVM under Windows CE on a 520 MHz hand-held device with at most 256 MB of memory. (The specs say 520 MHz; but runs slower in practice.) Thus we need a lot more control over object instantiation, as has been described.
    It would be nice to see a "use lazy initialization" checkbox for the auto-generated code. Or perhaps a "generate and use accessors" checkbox.
    Note that the following code contains a redundancy:
        private JLabel boardingPassLabel = null;The assignemnt to null is superfluous; it adds about 50 more bytes to the final class size (using Sun's javac). It can be omitted for class member variables.
    D

  • 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.

  • A good design for a single thread pool manager using java.util.concurrent

    Hi,
    I am developing a client side project which in distinct subparts will execute some tasks in parallel.
    So, just to be logorroic, something like that:
    program\
                \--flow A\
                           \task A1
                           \task A2
                \--flow B\
                            \task B1
                            \task B2
                            \...I would like both flow A and flow B (and all their launched sub tasks) to be executed by the same thread pool, because I want to set a fixed amount of threads that my program can globally run.
    My idea would be something like:
    public class ThreadPoolManager {
        private static ExecutorService executor;
        private static final Object classLock = ThreadPoolManager.class;
         * Returns the single instance of the ExecutorService by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getExecutorService() {
            synchronized (classLock) {
                if (executor != null) {
                    return executor;
                } else {
                    // TODO: put the dimension of the FixedThreadPool in a property
                    executor = Executors.newFixedThreadPool(50);
                return executor;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
    }The tasks I have to execute will be of type Callable, since I expect some results, so you see an ExecutorService interface above.
    The flaws with this design is that I don't prevent the use (for example) of executor.shutdownNow(), which would cause problems.
    The alternative solution I have in mind would be something like having ThreadPoolManager to be a Singleton which implements ExecutorService, implementing all the methods with Delegation to an ExecutorService object created when the ThreadPoolManager object is instantiated for the first time and returned to client:
    public class ThreadPoolManager implements ExecutorService {
        private static ThreadPoolManager pool;
        private static final Object classLock = ThreadPoolManager.class;
        private ExecutorService executor;
         * Returns the single instance of the ThreadPoolManager by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getThreadPoolManager() {
            synchronized (classLock) {
                if (pool !=null) {
                    return pool;
                } else {
                    // create the real thread pool
                    // TODO: put the dimension of the FixedThreadPool in a property
                    // file
                    pool = new ThreadPoolManager();
                    pool.executor = Executors.newFixedThreadPool(50);
                    // executor = Executors.newCachedThreadPool();
                    return pool;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
        /* ======================================== */
        /* implement ExecutorService interface methods via delegation to executor
         * (forbidden method calls, like shutdownNow() , will be "ignored")
          // .....I hope to have expressed all the things, and hope to receive an answer that clarifies my doubts or gives me an hint for an alternative solution or an already made solution.
    ciao
    Alessio

    Two things. Firstly, it's better to use     private static final Object classLock = new Object();because that saves you worrying about whether any other code synchronises on it. Secondly, if you do decide to go for the delegation route then java.lang.reflect.Proxy may be a good way forward.

  • Best Practice: passing properties to a Singleton

    Hi,
    I have an object in my app that must only exist once. It is a DatabasConnectionPool. I would like to implement it as a Singleton and access it from anywhere in the app with
    DatabaseConnectionPool dbcp = DatabaseConnectionPool.getInstance();
    But the thing is that I would like to pass it some settings: number of connections to the database, username and password, ...
    If I had a constructor for the class I would pass a Properties object with the constructor containig all the values but how do I do it with a Singleton?
    Right now I have:
    class Singleton {
    private static Properties _appProps = null;
    private static Singleton _instance = null;
    static public void setProperties(Properties appProps) {
    _appProps = appProps;
    static public Singleton getInstance() {
    if (null == _instance) {
    instance = new Singleton(appProps);
    private Singleton(Properties props) {
    So, the Launch code for the application reads the .properties files and calls:
    DatabaseConnectionPool.setProperties(props);
    WebServer.setProperties(props);
    LDAPServer.setProperties(props);
    Thanks a lot for your time guys!
    Rafa

    You don't need synchronization at all if you do it the way a previous post suggested:
    private static Singleton instance = new Singleton();
    public Singleton getInstance(){
        return instance;
    }This is lazy initialization by default because the singleton instance will only be created when the class is loaded into memory. It will be loaded into memory when you first call getInstance() so it's already using lazy initialization.
    The properties question seems to have several options
    1. Use your setProperties method to pass in dynamic properties. This will potentially make your singleton behave differently between uses if you change its properties while it's running.
    2. Hardcode the properties inside the singleton. This doesn't allow dynamic changes.
    3. Your connection pool is probably dishing out Connection objects and creating new ones when needed right? So, put the Connection creation in a different class called ConnectionFactory and pass in the factory to the singleton. This way you can customize the kind of connections to make in the factory without changing the singleton code. All the singleton cares about is saying factory.createConnection() and returning it.

Maybe you are looking for

  • 16:9 letterboxed project questions

    This is my first 16:9 project and it's a little confusing... My source footage is cropped to 16:9 aspect ratio from 4:3 but it's not anamorphic, it's only letterboxed. The frame size came out to be 720X404 when cropped and compressed with Compressor.

  • Mail attachment problem after service pack upgrade from 11 to 17 ECC 6.0

    Dear All, My mailing programs have started sending .dat file instead of .xls file. Earlier it used to go properly in .xls format. I'm using SO_NEW_DOCUMENT_ATT_SEND_API1 fm for mailing. Thanks. Edited by: User on Mar 7, 2011 12:37 PM

  • Problems deleting pdf's generated from files off of Snow Leopard Server

    The small design studio I work at has just upgraded from G5's running 10.4 Tiger, working off Tiger Server, to new iMacs running 10.6 Snow Leopard and a Mac Mini Server, on Snow Leopard Server. Normal working practice is to open files off the server

  • Help! I lost all my track numbers

    Playing with the Get Info I lost them all. Itunes still knows the numbers because I canb sort, but I can't display them. What can I do? dell   Windows XP Pro  

  • JBO datasources: avoiding literal SQL in where clause

    I understand that it is possible to set the where clause when defining a datasource with datatags: e.g. <jbo:DataSource id="ds" appid="wms_bc4j.Wms_bc4jModule" viewobject="WebUsersView" whereclause="USER_ID = 1"/> However this results in literal SQL