A way to make double-checked locking work?

First a little background.
I am writing an application that will run in an websphere/db2 environment. This application needs to provide a lot of referential data to the UI to properly populate certain fields (on the order of several dozen reference data requests per page request with about 3-400 concurrent users). To prevent 20 sql statements for a single user clicking a single link, I implemented a dynamic caching scheme with double-checked locking, not realizing the potential danger.
After reading an article I found on the pitfalls of double-checked locking (http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-toolbox.html), I still would like to prevent synchronizing on every cache request. I think I've found a solution that transfers the weight to the write operations, as those would be much less frequent and can therefore take the bigger load. I would like to see if anyone can find a hole in this.
public class DCLTest {
  private Resource rec = null;
  boolean initializing = false;
  public Resource getResource() {
    Resource temp = null;
    if (rec == null) {
      synchronized (this) {
        // initializing is now synchronized w/ main memory
        if (initializing)
          wait();
        if (rec == null) {
          // resource has lots of non-trivial datamembers that get initialized in the constructor
          temp = new Resource();
          initializing = true;
      // If initializing is true, we know it's set by this thread,
      // but still check that temp is valid
      if (initializing && (temp != null)) {
        synchronized (this) {
          rec = temp;
          initializing = false;
          notifyAll();
}The first synchronize block establishes the first set of boundaries. When it completes, the initializing flag is raised and any other thread waiting to enter that block will see the flag and wait. Also, when the block is executed, all of the resource object's internal fields get written to the main memory, but the "global" pointer will still be null. Once we enter the second synchronized block, we update the global pointer and reset the flag. Since both synchronized blocks synchronize on "this", calling notifyAll won't resume execution of the threads that are waiting until they re-acquire the lock on this, or in other terms, until the second synchronized block completes. By that point the initializing flag will be false, the rec field will be not null and rec's data members will be in sync between all threads trying to access it.
This all depends on the assumption that the optimizer won't combine the two synchronized blocks. If that's the case, the two synchronized blocks assure that the reference to rec is written (and made visible to main memory) after the actual contents of rec are in main memory. Therefore, if a reading thread acquires a non-null value in the check outside the synchronized block, it will acquirea proper value. Otherwise, it'll get a null and will enter the synchronized block and all is well.
This logic seems too good to be true (which unfortunately means it probably is), but I can't find the hole. The only justification my gut can give this is the fact that the write operation becomes slower than if both read and write were synchronized, which is acceptable in my case.

a big flaw (but easily solvable) is that there is no
guarentee that changes made to your "initializing"
variable
will ever be seen by other threads. It needs to be
marked volatile.this is not true. the JLS states that all threads are required to load from main memory on the first use of a variable in its lifetime. This would happen the first time a thread checks rec. When that check occurs, it will load from main memory and eihter get a null and enter the sync block, or get a valid reference and continue.
17.3 After a thread is created, it must perform an assign or load action
on a variable before performing a use or store action on that variable.
A second flaw is that you never set rec to anything
other then null.
( a single thread will enter the first synch block and
obtain a reference to temp. It will then NOT enter
the
second synch block as initializing is false. hence
your rec variable will be null)why is initializing false? it's set to true within the first block.
temp = new Resource();          
initializing = true;
Third.
rec is null. The first thread enters the first synch
block and stops before changing the initializing
valriable. A
second thread then tries to enter the synch block. It
cannot get the monitor and therefore yeilds. The first
thread then continues inside the synch block. It just
leaves the first synch block before being stopped. The
second thread then resumes. It obtains the lock on the
first sych block. initilaizing is false so it skips
the
wait() statment. Rec is still null so the second
thread creates a new one. Now you have two threads
each has
a local reference to different Resource's. Which one
gets used? (actually at the moment niether would
get used cos of the previous problem)the whole idea of initializing is that it never gets written outside of a synchronized block. if a thread cuts in just as the first thread left the first sync block, initializing is set to true, so it will simply wait. This is to make sure that no one does anything while the thread that's initializing is in between the two sync blocks.
i think you overlooked where initializing is set to true in the first block

Similar Messages

  • Double-Checked Locking

    Hey everyone,
    I posted a blog entry using Double-Checked Locking. Later one, Ryan commented to me that DCL does not work. See
    http://jroller.com/page/davinci/?anchor=lazy_initialization_with_less_pain
    I never knew that. Anyway, in a small efford to fix this I came up with the following code. Now one of the articles stated that many clever people already tried to fix the problem, and since I don't think I'm that smart, I guess this code also doesn't work. Can anyone explain to me why the following code could go wrong on some JVM's and platforms?
    private class Singeton {
      private static Singleton SINGLETON;
      private static boolean initialized;
      public static Singleton getInstance() {
         if (!initialized) {
           synchronized (Singleton.class) {
             if (SINLETON == null) {
               SINGLETON = new Singleton();
           initialized = true;
         return SINGLETON;
    }Thanks,
    Vincent

    Okay, this migth seem like a load of... well, you
    know, but in this case I force the JVM to initialize
    the object before setting the boolean to true, or
    not?Did you read the link I posted?
    "The most obvious reason it doesn't work it that the writes that initialize the Helper object and the write to the helper field can be done or perceived out of order. Thus, a thread which invokes getHelper() could see a non-null reference to a helper object, but see the default values for fields of the helper object, rather than the values set in the constructor.
    If the compiler inlines the call to the constructor, then the writes that initialize the object and the write to the helper field can be freely reordered if the compiler can prove that the constructor cannot throw an exception or perform synchronization.
    Even if the compiler does not reorder those writes, on a multiprocessor the processor or the memory system may reorder those writes, as perceived by a thread running on another processor. "
    Your code still fails. There is no known solution to the problem (if you can't create the singleton during declaration time)
    /Kaj

  • Fixing Double-Checked Locking using Volatile

    Oooh - what a scandalous subject title! :)
    Anyhow, I was expanding my knowledge on why the double-checked locking idiom used in Singleton classes fails (after reading that JSR-133 is not going to fix the problem!), when I read http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html and found a spicy section titled "Fixing Double-Checked Locking using Volatile" (at the very bottom of the document).
    As it is quite hard to find information (all sources revisit all the basic problems), I was wondering if anybody could back this up/refute it.
    Just one more thing. I anticipate that many people who are researching this matter would like to have this clarified, so it would be beneficial to keep posts very much on topic. There is already a lot of information available about double locking failures in general.
    The problem this post faces lies in a lot of statements saying "using volatile will NOT fix double-checked locking" that refer (I think) to the current JDK.
    Thanks heaps!

    Volatile only checks that not more than one thread is accessing the variable at the same time (amongst other things of course), so in the example, it could cause problems. Let me explain a little here. Given a situation where two threads wish to aquire the Helper:
    Step 1: Thread 1 enters the method and checks the helper status
    and sees that it is null.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 1 requires helper, and sees that it is null
         synchronized(this) {
            if (helper == null)
               helper = new Helper();
       return helper;
    }Step 2: Thread 2 enters the method, before the lock can be
    acquired on the this-object and notices that the helper is
    null.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 2 requires helper also
         synchronized(this) { // and it is still null
            if (helper == null)
               helper = new Helper();
       return helper;
    }Step 3: The first Thread creates a new Helper
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 2 waiting for lock realeas
         synchronized(this) {
            if (helper == null)
               helper = new Helper(); // <!-- Thread 1 creating new Helper
       return helper; //
    }Now for Step 4, there are a few possibilites here. Either Thread 1 returns the helper it created, or Thread 2 can create the new Helper before the Thread 1 returns the Helper. Either way, the result is unwanted.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) {
         synchronized(this) {
            if (helper == null)
               helper = new Helper(); // <!-- Thread 2 creating new Helper
       return helper; // <!-- Thread 1 returning Helper
    }The code can also create interesting situations (deadlocks?) due to the synchronized(this) statement used in a ... creative way in this case.
    I might be wrong of course. Just my �0.02.
    Tuomas Rinta

  • HT204368 any way to make an iphone4 to work with Skype via bluetooth?

    any way to make an iphone4 to work with Skype via bluetooth?

    I have a Samsung HM1500. i don't know if it has 2dp. I guess it doesn't, 'couse otherwise would have work, wouldn't it?
    Any other way to fix this?
    Why doesn't Apple make a softwear update to solve this kind of problems?
    And do you have any idea how to set up diferent tones and for diferent applications - for istance Skype?
    Thank you very much for your help.

  • Double check locking using Volatile.

    Hi gurus,
    Please suggest if the following lazy loading would work.
    public CommandFactory{
           private static volatile ICommand command= null;
           private static ICommand instanceCommand = null;
           public static ICommand getCommand(){
                      if(instanceCommand == null){
                             synchronized(CommandFactory.class){
                                  if(instanceCommand == null){
                                      command = new Command();
                                      instanceCommand = command;
               return instanceCommand;
    }

    For danny like "Boss of Talented people..lol...lmao....." understand
    The Double checking with Volatile which would work with the new improved volatile contract.
    public CommandFactory{
           private static volatile ICommand command= null;
                  public static ICommand getCommand(){
                      if(command== null){
                             synchronized(CommandFactory.class){
                                  if(command== null){
                                      command = new Command();
               return command;
    }And the code I wrote which isn't any good as per JTahlborn is here
    public class CommandFactory {
         private static volatile ICommand command = null;
         private static ICommand instanceCommand = null;
         public static ICommand getCommand() {
              if (instanceCommand == null) {
                   synchronized (CommandFactory.class) {
                        if (instanceCommand == null) {
                             command = new Command();
                             instanceCommand = command;
              return instanceCommand;
    }

  • What is the best way to make 3g/4g simcard work with airport extreme

    I live in Mumbai, India and I am tired of the state of broadband connection over here. I have vodafone 3G Data only SIM with me which I use via a 3G dongle that plugs into my mac. It has a decent speed and I would like to use it as a primary internet connection across the 3 iPhones, 2 iPads, a Mac and 2 apple tvs at my home.
    I have a 2014 airport extreme and i want to know what hardware do i need to make the 3g sim work with it? like put the sim in the hardware/adapter and then plug it into the wan port of the airport extreme and let the AE handle my dhcp so that i can access 3g internet from all my devices?
    also, i was something 4g compatible as 4g is on the roll in India. it doesn't have to be a wireless router on its own but something that can dial the connection and provide internet access to the AE via the wan port.
    thanks.
    Neerav

    The only reason I mention it would be configure your network for a roaming instead of extended setup. The number one advantage over an extended is bandwidth performance ... aka speed.
    For example, I have a Cisco RVS4000 wired router as my main Internet router. I am fortunate that my 2-story home came pre-wired for Ethernet. I have placed an AirPort Extreme and a Time Capsule, connected by Ethernet back to the Cisco; one on each floor to provide a seamless wireless network for an assortment of wired/wireless clients. With this setup, I am able to stream HD TV content throughout the house. Mine is an example of what you can do with a roaming network.

  • Is there a way to make an inline remote work as a menu button?

    My menu button on my 4th gen iPod touch is currently half-stuck.  The bottom half doesn't come up, the top half still works.  So I have my menu button working still, but I'm trying to find a way to not use it, just in case.
    is there any way to change the settings for the inline remote on my headphones?  You press the center button once, it plays, twice it skips, three times it goes backward.  Is there anyway to reset one of those to act as the menu button?  or adding other inline remote commands?    

    Only the carrier that the phone is locked to can unlock it. Contact Sprint.
    Cheers,
    GB

  • Is there a way to make the Markers panel work better with the Source panel?

    My workflow is to first cut a multi-cam project (but it could be any long clip), then watch it all over again to make notes about what to keep and what to kick.  So after I'm done cutting the initial rough cut of the entire hour or two of footage, I'll set focus to the Markers panel and begin watching the entire clip from the beginning to make notes as markers within the clip. 
    I'll play the clip back in the Source monitor and when something interesting happens, I'll type "M" on the keyboard.  This places a marker in the clip (or multi-cam clip in my case).  Without stopping the clip, I'll pick up my mouse and tap the Markers tab in the notes section for the last marker laid down.  I'll type a note (something like "S" for interesting "Shot" or "HUGS" or "DANCING" to indicate the main action occuring at this point in the clip, or "Mike:  Are we there, yet?" for a key dialog point).  Next, I'll move my mouse back to the Source panel (the video has not stopped this entire time) and give any gray area of the Source panel a tap just to activate it.  I'll watch for the next point of interest and repeat the process.  M to mark.  Move to the Markers panel.  Tap the last marker.  Type some notes.  Move back to the Source panel and tap to give the panel focus.  This works fairly well, but could be tuned, with just a few options, to make it more streamlined for this type of use.
    What I'd like to be able to do is never leave the keyboard AND use minimal keyboard shortcuts.  A perfect workflow might be:
    1. Start playing the clip in the Source panel.
    2. Type "M" to drop a marker.  Focus would AUTOMATICALLY move to the notes section of that marker within the Markers panel, while the video continues to play on in the Source panel.
    3. I type my notes into the Markers panel and hit Enter, or CTRL+Enter, which returns focus to the Source panel.
    This would allow me to quickly build a list of markers and notes about a clip or sequence without ever stopping and without once touching my mouse (unless I get behind and need to backup).  Currently, the only time I really get behind is when clicking on a window and not realizing that focus was not given to that window, so that when I hit "M" again, for example, I don't actually create a new marker, but rather add the letter "M" to my most recent Marker note.
    All of this seems a very common task for anyone who works in reality TV, or even event videography.  Who's with me?  Can this be done already?  If not, I'll submit a feature request.  How would you make this feature better?

    Sounds like you did this on the fly.
    MM is supposed to open the Marker Panel Dialogue
    M just sets a marker
    Not sure if either are intended for on the fly during playback .
    There is also a Marker Icon on the Source Window Pane  >>

  • Is there a way to make Wake on Demand work?

    I have checked the AKB and I have a Mac Pro that is all set to wake on demand, the only issues is that I have an older Airport Express (b/g not n). Does anyone know of a work around to get this Airport to work with Wake on Demand, or am I out of luck?

    There are many Sleep related problems on these boards just search them out here in Discussions. You can try troubleshooting steps like disconnecting all peripherals, creating a new user account to see if it is systemwide or limited to your user account. If it is you might try dragging yourname/Library/ "Preference" folder to the desktop and restarting to see if it is a pref...
    In short I'm not sure I can solve your issue but I can offer a good workaround.
    If your Mac is only troublesome with Sleep, you might like to know that sleep is a very unnecessary state.
    If you choose to leave your Mac on 24/7 it uses very little power over "Sleep" as the HD and fans spin down quickly when not in use and you will use Screen Sleep. The advantage of being on 24/7 is there are Periodic scripts (daily, weekly and monthly housekeeping tasks) set to run between 3 - 5 AM. If you do not leave your Mac on these Periodic scripts will not run. If you "Sleep" your Mac they will not run either.
    Another advantage is that your Mac is ready to respond at the touch of a key move of a mouse with no "grogginess". And yet another, of course, is you will suffer no Sleep related problems.
    Just set your Mac to "Never Sleep" and "Screen Sleep" to whatever you like and don't worry.
    For security reasons you may want to log out.
    As for shutting down, each time you reboot your system you can cause damage. A computer running Unix should never need to be rebooted, of course this can't be helped but theoretically it should never need rebooting. Each time you reboot you can send a power surge through your CPU, HD, etc which could cause problems and shorten the life of your computer.
    fyi - some Unix servers have been up and running for over a dozen years. There also have been many posts here in Discussions where folks were posting their "up" times.
    -mj

  • Is there a way to make keyboard text shortcuts work better?

    For example: omw = On my way!
    On iOS these work accross the board, but on OS X they only seem to work on certain applications. Such as TextEdit, but have limited or no use in other applications. They work ok in the URL bar in Safari, but try to use them in a text field (such as the one I'm typing in now) and they don't work. It's especially irritating when I try to log into a website, and I can't use my custom shortcut for my email address. I can easily do this on iOS, but not OS X.
    Is there any way I can get text shortcuts to behave better on OS X, or is this a hopeless dream...
    If you don't know how to access them, it's:
    System Preferences -> Keyboard -> Text (OS X)
    General -> Keyboard -> Shortcuts (iOS)
    It's great that they sync accross both platforms, but it's pointless if I can't use them on properly on OS X.

    Sounds like you did this on the fly.
    MM is supposed to open the Marker Panel Dialogue
    M just sets a marker
    Not sure if either are intended for on the fly during playback .
    There is also a Marker Icon on the Source Window Pane  >>

  • Is There A Way To Make The "Check Out CNN On Twitter" Pop-Up Stop?

    I had an old DVR that I had to get rid of and before that I got this annoying pop-up to stop appearing but it's been weeks with my new DVR and no matter what I do it keeps popping up on the screen. Sure, you just hit 'exit' on the remote and it goes away but it keeps coming back and I'd like to know how to disable it.
    Just to note, I have gone into the menu --> settings --> PopUp Alerts and have set it to "Never Show Me Again." Is there something else I should be doing???
    Solved!
    Go to Solution.

    Hi bushleaguer,
    I believe that you are referring to the Interactive TV information that pops up in the upper right corner of the screen several seconds after tuning to channels such as CNN and History. I find these to be extremely annoying and was thrilled when I finally discovered how to get rid of them. This function can be disabled by following this path:
    Menu > Settings > Television > Interactive TV > Disable > OK > Exit
    Hope this helps.
    FYI - I do not have PopUp Alerts disabled.
    Find this post helpful, informative or just something you agree with? Click the red ‘thumbs-up’ button.
    Did this post solve your problem? Click the green ‘Accept as Solution’ button.

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

  • Make a check box in LiveCycle with a personal character or image as check mark ( info to share...)

    Hello everybody,
    It makes now several weeks i go trough the different forums to find a way to make the check mark of a check box in LiveCycle with a personal color instead of the default black mark, that seems to be the only option available.
    I saw somebody else with that question, but no answer.
    So i found a work around, that make the check box really flexible.
    Here it is:
    REMEMBER that this will work only with forms saved as dynamic PDF.
    Open a new form in Livecycle.
    1) Open Library panel ( Shift+F12) and select Check Box and put it in the page with the dimension and position you like and select it.
    Open the Object panel ( Shift+F7), select field section and under Caption make it blank. Select Binding Section and under name write in ' CheckBox '. for the rest leave all the section values as they are.
    2) In Library select, in the standard section, the icon for making a text object. Put it in the page and size it to your needs and put it on the top of the CheckBox. Select it.
    In the Object Panel, Draw section and under Presence 'Visible'.
    Open the Font panel ( Shift+F4) and under font section, Font : select the Wingdings font and choose the symbol to use as the mark, under Size : the size you need, under Style: font color you like. If the result of the mark is to your feel, set the object to 'invisible'. Leave all other values as they are.
    Open the Hierarchy panel (Shift+F11), right click on the static object and rename it to ' CheckMarkModel ' .
    For information : changing the text object to an image object let's you use an image for the mark in the checkbox.
    3) In Library, select in the standard section the icon for making a Button. Put it in the page and size it to the CheckBox dimension and put it on the top of the text object. Select it. In the Object panel, under Caption : make it blank, under Appearance : select custom in the drop down list an in the dialog box that comes up set the edges to none and the
    background to none. Leave the rest as it is.
    Open the Hierarchy panel (Shift+F11), right click on the Button object and rename it to ' ClickCheckBoxButton ' .
    Now open the Script Editor (Shift+Ctrl+F5), on the left under Show : select in the list the ' Click ' event, under Language : select JavaScript, copy to the window the following script :
    if (CheckMarkOnOff.rawValue == "0")
    CheckMarkOnOff.rawValue = "1";
    CheckMarkModel.presence = "visible";
    else if (CheckMarkOnOff.rawValue == "1")
    CheckMarkModel.presence = "invisible";
    CheckMarkOnOff.rawValue = "0";
    4)Now put in the page an other Check Box, put it on the top of the Button object and select it. In the Object panel, Field section, under Caption : make it blank, under Appearance : none, under Presence : invisible, let the rest as it is. In the Value section, under Type : Read Only, under Default : Off. In the Binding section, under Name : name it CheckMarkOnOff, leave the rest as it is.
    5) So you have now four objects in the page 1. In the Hierarchy panel set each object by dragging them in
    this order :
    CheckBox
    CheckMarkModel
    ClickCheckBoxButton
    CheckMarkOnOff
    In the form select all the objects and group them. If you copy the group as many times you need you automatically will have an other Check Box, ready to work.
    So here you are with an personal Check Box.
    Don't forget to set the preview PDF to dynamic under Menu /File/Form Properties, the in the dialog box that shows up /Default tab and under the XDP Preview format : select in the list an Acrobat Dynamic form.
    REMEMBER that this will work only with forms saved as dynamic PDF.
    If somebody from Adobe could upload the sample file i made, to the forum, so that anybody can download it to his computer, would be appreciated, email me at : [email protected] .
    Regards Mike.

    I also faced this same problem and there is an actual solution but it involves modifying the xml source for the checkbox - however it is a simple modification so if your not familiar with editing the xml source don't worry about that. <br /><br />Click on the checkbox you want to modify and then click on the XML Source tab. LiveCycle will take you to that point in the XML. <br /><br />Now, scroll down until the close of the ui node( </ui> )within the checkbox field and modify the font node to look like the following:<br /><br /></ui>  -- close of UI node<br /><font typeface="Arial"><br />   <fill><br />      <color value="0,0,255"/><br />   </fill><br /></font><br /><br />This produces a checkbox with a blue check mark. <br />You can, of course, make the color any RGB number you want.<br /><br />You can then save that field in your library and reuse it anytime you want and it will always have that color checkmark. <br /><br />Good luck. <br />-Andrew

  • I just got a notification that the phone of somebody I don't want on my imessage account, has been added to my account. how do i double check that they are indeed on my account, and then remove them?

    I just got a message on my computer and my phone that an ex girlfriend of mine's phone was just added to my imessage account. For obvious reasons, I'm not okay with that. I just messaged her on facebook and double checked if the name of the phone sent to me is the label of her phone, and it was. She then sent me a screen shot of her phone's imessage settings page though saying that its only connected to her account. I dont believe that she is lying to to me, but I dont believe my computer is either. Is there a way I can double check what devices are linked to my accccount and remove one if need be?

    Hi Connor,
    The only "accounts" on iMessage are the accounts you have set up. Open iMessage, from the top toolbar click on Messages>Preferences>Accounts
    There you will see what accounts are set up on your iMessage app. If your ex-girlfriend is still set up in your Contacts, you may want to remove her from there.
    Cheers,
    GB

  • How to make Firefox 3.6 work with jinit 1.3.1.26

    Hi All,
    Can somebody help me out on this,I know JINIT is desupported but is there a way to make firefox 3.6 work with jinit 1.3.1.26.
    bcos my customet dont wanna move to Native java as they had some issues with NAtive java.
    any help would be appreciated.
    Thanks & Regards
    S

    Hi,
    What is the applciation release?
    Refer to these documents to verify if you are running on a certified client combination:
    Note: 389422.1 - Recommended Browsers for Oracle E-Business Suite Release 12
    Note: 285218.1 - Recommended Browsers for Oracle E-Business Suite 11i
    Regards,
    Hussein

Maybe you are looking for

  • How can I add a new WLC on my network

    Hi there, I have a WLC4404(v4.0.219.0) and several APs on my network. Those APs are belonged to a couple of vlans. I planed to add a new WLC4404(v5.0.148.0) on same network with a old one. I configured the new WLC4404 as a primary controller of the A

  • Safari won't open pdf

    I installed Adobe reader 7 in an attempt to run a website that said it needed it, however when it didn't work I deleted the application. Now when I try to open pdf files in Safari it comes up with a blank page. How do I get Safari to open PDFs like i

  • Retrieving and removing Messages and Activities

    Hi, In our project we would like to create alerts and simple workflow. We would like to base our implementation on the existing B1 infrustructure. For that we need to manipulate messages and activities (i.e. contacts). Alas I did not find for SAPbobs

  • VLO60-list of outbound deliveries.

    Hi Gurus, In the transaction code: VL06O, I selected the tab list of out bound deliveries and executed. In the output report I got  Delivery number details , ship-to party  data, GI Date ,Deliv.date .But Iam not getting the   Serial number data. Can

  • How do I stop iPhoto from opening with an iPhone?

    I tried to do this on Yosemite but these steps don't work. Is this a bug? Step 1: Open iPhoto. Step 2: In the Menu bar, go to iPhoto > Preferences- Step 3: For the "Connecting camera opens" option, make sure to select "No application." Step 4: Close