WeakReference is cleared while other references are created

Is it possible that while a weak reference is being cleared, another reference is created to the object, resulting the get() method of the reference to return null although the object still exist in memory? I have the following example code:
WeakReference ref = new WeakReference(new Object());
Object obj1 = ref.get();
Object obj2 = ref.get();
if(obj1 != null && obj2 == null)
System.out.println("obj1 is not null and obj2 is null!!!");
}Is it possible that the reference is cleared in parallel to this code, means that GC started cleanup and in the mean time the code calls the first get() and has a reference, while the second get() is after the cleanup and will return null? I'm seeing this in a more complex code that I have but didn't manage to reproduce it with a simple case. I'm using weak references for caching and at some point have a "miss" in the cache although the object is still in memory and has referneces.
Thank you!
Noam

I do like to have the behavior of WeakReference in my application since soft references cause the application to consume large amount of real memory and this is a problem (it'll prevent other applications from using this memory).
Here is more detailed code - below is the class which is used for caching. I might be able to replace it with WeakHashMap - I'll also try it. But basically, it gives the same functionality.
public class ReferenceCache implements IAlarmClockRegistration
     private static Logger log = Logger.getLogger(ReferenceCache.class);
     public static final long DEFAULT_CLEAN_INTERVAL_MILLI = 1 * 60 * 1000; // 1 minute
     public static final int REFERENCE_TYPE_STRONG = 1;
     public static final int REFERENCE_TYPE_SOFT = 2;
     public static final int REFERENCE_TYPE_WEAK = 3;
     private long m_lCleanIntervalMilli = DEFAULT_CLEAN_INTERVAL_MILLI;
     private Map m_mapReferences = new HashMap();
     private ReferenceQueue m_rqQueue = new ReferenceQueue();
     private int m_iReferenceType;
   public ReferenceCache()
        this(REFERENCE_TYPE_WEAK);
     public ReferenceCache(int iReferenceType)
         m_iReferenceType = iReferenceType;
         register();
     private Reference createReference(Object obj, String key)
          switch(m_iReferenceType)
               case REFERENCE_TYPE_STRONG : return new StrongReferenceWrapper(obj, key, m_rqQueue);
               case REFERENCE_TYPE_SOFT   : return new SoftReferenceWrapper(obj, key, m_rqQueue);
               case REFERENCE_TYPE_WEAK : return new WeakReferenceWrapper(obj, key, m_rqQueue);
               default: throw new RuntimeException("unknown reference  type");
     public synchronized void put(String id, Object obj)
          if (log.isDebugEnabled())
               log.debug("put() - id=" + id);
          Reference ref = (Reference)m_mapReferences.get(id);
          if(ref != null)
               ref.clear();
          m_mapReferences.put(id, createReference(obj, id));
     public boolean referenceExists(String id)
          if (log.isDebugEnabled())
               log.debug("referenceExists() - id=" + id);
          Reference ref = (Reference)m_mapReferences.get(id);
          return (ref != null);
     public synchronized Object get(String id)
          if (log.isDebugEnabled())
               log.debug("get() - id=" + id);
          Reference ref = (Reference)m_mapReferences.get(id);
          if(ref == null)
               log.debug("get() - ref is null");
               return null;
          return ref.get();
     public synchronized void clear(String id)
          if (log.isDebugEnabled())
               log.debug("clear() - id=" + id);
          Reference ref = (Reference)m_mapReferences.get(id);
          if(ref != null)
               ref.clear();
               m_mapReferences.remove(id);
               synchronized(ref)
                    ref.notify();
     private synchronized void clean()
          log.debug("clean() - [in]");
          Reference reference = null;
          while (null != (reference = (Reference) m_rqQueue.poll()))
               String key = ((IReferenceWrapper)reference).getKey();
               m_mapReferences.remove(key);
     private void register()
          AlarmClock.getInstance().register(m_lCleanIntervalMilli, this);
     public void wakeUp(long id)
          try
               clean();
          catch(Throwable t)
               log.error("wakeUp() - caught exception", t);
          finally
               register();
}This is how the cache is used:
     public boolean store(IDirectoryEntry entry) throws Exception
          synchronized(m_lckRefMap)
               // here there is some code to store object on disk
               m_cache.put(entry.getUniqueID(), obj);
               return true;
     public Object retreive(String strKey) throws SQLException
          synchronized(m_lckRefMap)
               // look in the cache first
               IDirectoryEntry entry = (IDirectoryEntry)m_cache.get(strKey);
               if(entry != null)
                    return entry;
                                                // here there is a code to read object from disk
              }

Similar Messages

  • Error: 1013020 Cannot clear data for database [Daily] while other users are

    I'm trying to clear a (BSO, v 11.1.2.1) database, and it's failing with the following message:
    Error: 1013020 Cannot clear data for database [Daily] while other users are connected.
    There are no other users connected first of all. Second of all, I've never had a database fail to clear just because other users were connected. Has anyone seen this before?
    Sabrina

    WHen ever u start essbase application ..there is services starts in task manager called "ESSSvr" . The number get increased when keep opening as number of application you open ..So what i say is when u see no users in sesssion and no batch runs ahead , u can stop the Application in EAS and automatically it will log off all the users from that respective application ..And then start again the application and u can perform ur task
    this usually happnes when some one is connected with excel addin or Same EAS open by another user remotely..thats what i have seen in my exp's

  • I can't get my player to play videos while other apps are open IPAD 4gen

    I can't get my player to play videos while other apps are open IPAD 4gen
    Whenever, I have pages open or any other app I press the home button twice, and then I swipe to the right and obtain the menu that allows me to alter brightness or sound. At this point I press play and nothing works. However, once I go back to my youtube page, and press the play button then it works. If anyone could help me that would be greatly appreciated. Thank you so much.

    just click the serial number in itunes ... geeze... just kidding
    you might be able to find it on the mac...
    in finder do your username under places then library then application support then MobileSync then Backups
    the shortest folder name should be the UDID
    of course that assumes it ever made a backup...
    if it made more than one there will be some -date-blah on the end...

  • Opening another env handle while other operations are in progress

    Dear community!
    1. When I am performing some long operations on a container, I also open another env handle for the same environment in the different process. Then the opening of the second handle crashes the application. Am I allowed to do so, or just I misconfigured my environment?
    This is my configuration code.
    EnvironmentConfig envConf = new EnvironmentConfig();
    envConf.setAllowCreate(true); // If the environment does not
    // exits, create it.
    envConf.setInitializeCache(true); // Turn on the shared memory
    // region.
    envConf.setInitializeLocking(true); // Turn on the locking subsystem.
    envConf.setInitializeLogging(true); // Turn on the logging subsystem.
    envConf.setTransactional(true);
    envConf.setErrorStream(System.out);
    envConf.setRegister(true);
    envConf.setRunRecovery(true);
    log.debug("Opening DB environment at " + envHome.getAbsolutePath());
    Environment tntEnv = new Environment(envHome, envConf);
    2. And the second question. Does EnvironmentConfig object affect Environment itself, in other words can I use differently configured EnvironmentConfig objects when opening environment at the same time (in multiprocess applications)?
    Thanks in advance
    Vyacheslav

    Vyacheslav,
    (1) what crash do you see? generally speaking Berkeley DB will "join" an existing environment and ignore your current configuration if an environment exists in the directory you specify.
    (2) no, you can't do that and if the system doesn't return you an error you will see problems somewhere along the way.
    One thing you MUST NOT do is to run recovery in more than one thread. I think that may be your problem. It looks like you are specifying runRecovery(true) in the new environment -- this will certainly crash (or lead to non-deterministic errors) a running application. Recovery may only be run by one thread at a time, with exclusive access to the environment.
    Regards,
    George

  • Not getting Admin Alerts while other Admins are

    I installed Spiceworks a while back but didn't really use it much. Now our organization is expanding and I've added a couple more admin users. That's when I realized that I no longer am receiving any Admin Alerts. The other two Admins are getting them just fine. I'm assuming at one point I disabled alerts for myself since I wasn't using Spiceworks, but now I can't figure out how to turn them back on. Everywhere I look it appears the alerts are enabled for my account, but I'm still not receiving any while the other admins do.When I go to settings -> user accounts, my notify is set to all.When I go to settings -> monitors & alerts, I see my name at the top along with the other two admins "will receive an email alert for all monitors....", but only the other two admins are getting the alert.I'm obviously missing something, I just don't...
    This topic first appeared in the Spiceworks Community

    Having the exact same problem. Tried Apple support multiple times and all they suggest is to remove and the add the account again. Which doesn't fix it.
    Here is a possible workaround. Google exposes a tool that lets you choose which calendars to expose via CalDav: https://www.google.com/calendar/syncselect
    I've deselected all but my own calendar, which I would think solves this. Now of course you can't see the other calendars in CalDav apps, but that's better for me than the eternal alerts.

  • Someone tempered with my computer,whenever i open youtube or facebook it says unable to open page while other websites are opening.what i can i do to remove ths

    youtube and facebook not opening.just saying unable to open the page even after clearing the cookies and cache

    Hello,
    In order to better assist you with your issue please provide us with a screenshot. If you need help to create a screenshot, please see [[How do I create a screenshot of my problem?]]
    Once you've done this, attach the saved screenshot file to your forum post by clicking the '''Browse...''' button below the ''Post your reply'' box. This will help us to visualize the problem.
    Thank you!
    Start '''[https://support.mozilla.org/en-US/kb/troubleshoot-firefox-issues-using-safe-mode Firefox in Safe Mode]''' {web Link} by holding down the '''<Shift><br> ''(Mac Options)'' ''' key, and then starting Firefox. Is the problem still there?

  • My handoff phone call does not work with Yosemite while other apps are working

    I have upgraded to Yosemite and tried the handoff with my iPhone 6. First time I tested phone call which worked. I switched off the Mac and went out. When I came back the handoff phone call didn't work anymore, while Safari, Email, etc. are still working via handoff.
    Thanks for any help in advance

    The iPhone calling feature is not called, "Handoff." Using the terminology incorrectly only adds to the problem. "Handoff," is the feature where apps share documents.
    Both "Phone" and "Handoff" are separate features under "Continuity."
    This is "Handoff":
    This is "Phone" calling:
    Continuity features (Scroll up and down to see all): http://www.apple.com/osx/continuity/

  • IPhone 4 not connecting to WiFi while other iDevices are!

    My mum's iPhone 4 8GB is being extremely tempermental, If I'm 1 or 2 meters near the router, It'll connect. If i move away it loses signal. My other iDevices(iPod Touch, iPad ) can still get reception from the other side of the house which is a good 25 meters away from the router.
    Anyone encountered this problem before? Any solutions
    Btw, it's relatively new and has had the fault since it was brought. My mums just been to lazy to go to book an appointment at the genius bar.

    Hello HeatherO,
    Thanks for using Apple Support Communities.
    From your post I understand that you are connected to your Wi-Fi network but are unable to access the internet.  It is possible you may have a self-assigned IP address from your modem/router.  Take a look at the information below for troubleshooting steps.
    Unable to access the Internet while connected to Wi-Fi
    If you're using a public or commercial network, you may need to log in or subscribe.
    Check to see if you have a self-assigned IP address:
    Tap Settings > Wi-Fi and locate the Wi-Fi network to which you're connected and tap .
    If your IP address is 169.254.xxx.xxx, you may not be able to access the Internet.
    If you do not have a self-assigned IP address, see if other Wi-Fi devices on your network have Internet access.
    If they do not, consult with your network administrator or ISP for further assistance.
    If they do, reset network settings on your device by tapping Settings > General > Reset > Reset Network Settings. Note: This will reset all network settings including:
    previously connected Wi-Fi networks and passwords
    recently used Bluetooth accessories
    VPN and APN settings
    iOS: Troubleshooting Wi-Fi networks and connections
    Take care,
    Alex H.

  • Adobe Reader XI 11.0.06 - launching this takes 5 seconds while other users are instant or 1 second.  Need troubleshooting tips or idea's

    It was at 6 to 10 seconds but I unchecked Enable Prtoected Mode at startup and unchecked Enable Enhanced Security.
    Looking for more idea's / suggestions to getting this to open instant / 1 second.
    Impacting several users.
    Win 7 Enterprise SP 1
    Intel i5 1.60 GHz
    64-bit OS

    Thank you for the response, I have tested just clicking on Adobe Reader XI version 11.0.07 and it is launching in 4 to 6 seconds.
    While I do see some improvement I'm still at a loss of why some users can instantly launch this application in (1 second or less) with the same hardware and I have several users still at a 4 seconds.
    I am going to log in as admin and stop some of our services and other background apps and test launching.

  • Keeping menu tree form session connected to DB, while other forms are open

    When our application starts, a menu tree module is opened, which contains a list of modules that users can open. When a user click on a module to open, the code will issue the command open_form (…,…., session). So every form is opened in its own session. The maximum idle time allowed in a session is 45 minutes. Therefore after setting idle for more than 45 minutes any module including menu tree module will lose connection to the database. So if a user open a module from the menu tree module and spend more than 45 minutes working on that module, when the user go back to the menu tree module, they get an error that menu tree module lost connection to the database. So the question is, how to keep the menu tree module session connected to the database, even if it exceed the maximum idle time as long as other modules sessions are still connected to the database.
    1. set maximum idle time allowed in the database for 5 minutes
    2. open form A
    3. open form B from form A in it own session (OPEN_FORM (...,...,SESSION)
    4. work on form B for more than 5 minutes
    5. go back to form A,
    6. fom A has been disconnected from the database
    I have tried to use the timer, but the problem with timer is when a timers fire in forms that
    do not currently have focus, and a context switch is performed. The form flickers when the context switch is made, and the current item text becomes selected when focus returns to the
    current form, which will cause problem to the users.
    Our client setup the database timeout for security reason, and therefore, it cannot be replaced by TIMEOUT PJC.
    Keep in mind that we have 600 forms and the application is already in production.
    Thanks

    Thank you Manu
    I added the following code logic to when-window-activated
    if menu-tree still connect to the DB then
    do nothing
    elsif lost of connection is due to exceeded maximum idle time then
    if the global.last_closed_forms_transaction < 45 minutes
    or if there is form that is still connected to DB then
    logout;
    login;
    else
    messagebox ( exceeded maximum ideal time allowed )
    end if;
    else
    messagebox ( lost connection due to network error)
    end if;
    Thanks
    Edited by: user7591510 on Aug 7, 2009 4:58 AM

  • Why the iTunes on my ipad3 freeze a lot while other features are functionning fine?

    I tried to download free episodes from podcast and after I exited, I can not go back in to iTunes.  The icons on the iTunes all freeze, I can not select any of them. If I click the music icon from the home page of the iPad, then iTunes move to stay ont the music, can not go to any other icons. I just bought the iPad yesterday and this is the second time it happened.  The first time it happened, it was back to function after three hours.  Can someone tell me what could go wrong? Thanks much

    Bump, I really need an answer. Please help out!

  • All chinese input become numbers using firefox, while other browers are doing fine

    when using Chinese input methods, google pinyin or MS pinyin, I cannot write chinese characters, the input all become numbers. This is a lenovo laptop, all other browers work fine on this laptop.
    But firefox works fine on other computers, i can write in chinese in firefox on other cumputers.

    I have pavucontrol and I see the audio sources appearing when playback starts.
    When I have one audio source playing and I start another, for a fraction of second the sound skips and cracks as if part of the sound buffer got corrupted.
    EDIT: I just realized another thing : I have the same setup: I start audacious, push play, music plays, then I start gnome-music, push play, hear skip/corruption/crackle. Now the gnome-music plays the song, I pause the song and realize the volume of audio stream from audacious went down. When I close gnome-music, it gets restored again. I am not sure whether this could be the cause. Also I this probably shouldn't happen at all - I mean the audio should be suppressed during notification sounds but not during playback from another app, right?
    Last edited by klement (2015-01-28 16:31:51)

  • Extremely low-res pics when copied to photostream while others are fine?

    I have some downloaded iPad (New iPad, iPad 3) wallpaper images that I copied to Photo Stream so I could use them on my new iPhone 5. Some of the images copied just fine, while other pictures are low resolution &amp; very pixelated. I thought maybe I was trying to copy too many at once. So I deleted the bad ones and tried again, copying each pic one at a time. They still show on Photo Stream at very low resolution. Does anybody know why, and what I can do to fix this?

    OK, I guess I figured it out...
    Below is a sample of one of the images I was trying to put on Photostream.
    The problem must be something with iOS, because the garbled image on the left only looks that way on the iPad 3 & iPhone 5. When accessed from my PC, the same image is at full resolution (2048x2048). And then when I upload the same image back to Photostream, it still gets resized to 1536x1563, but at much better quality as can be seen in the image on the right.
    I'm glad I found a workaround, but it's very annoying that it doesn't work the way it is supposed to.

  • Why one user can not see plan output for some orgs while other users can?

    We have several inventory/planning orgs. Suddenly one of the users is not seeing any plan output for some organizations. While other users are able to see plan out (planner workbench) for all org.
    All users use the same responsibility.
    Deleted all the folders to eliminate hidden query in default folder.
    Any other thoughts?
    Edited by: 918894 on May 5, 2013 10:22 PM

    The issue is resolved.
    In the user preferences, one user has Inventory Category Set and other user has Planning Category Set as the default. Items belonging to one Org were not assigned Planning Category Set. Thus they were not showing for the other user.
    Thanks for the response.

  • Why multiple  log files are created while using transaction in berkeley db

    we are using berkeleydb java edition db base api, we have already read/write CDRFile of 9 lack rows with transaction and
    without transaction implementing secondary database concept the issues we are getting are as follows:-
    with transaction----------size of database environment 1.63gb which is due to no. of log files created each of 10 mb.
    without transaction-------size of database environment 588mb and here only one log file is created which is of 10mb. so we want to know how REASON CONCRETE CONCLUSION ..
    how log files are created and what is meant of using transaction and not using transaction in db environment and what are this db files db.001,db.002,_db.003,_db.004,__db.005 and log files like log.0000000001.....plz reply soon

    we are using berkeleydb java edition db base api, If you are seeing __db.NNN files in your environment root directory, these are environment's shared region files. And since you see these you are using Berkeley DB Core (with the Java/JNI Base API), not Berkeley DB Java Edition.
    with transaction ...
    without transaction ...First of all, do you need transactions or not? Review the documentation section called "Why transactions?" in the Berkeley DB Programmer's Reference Guide.
    without transaction-------size of database environment 588mb and here only one log file is created which is of 10mb.There should be no logs created when transactions are not used. That single log file has likely remained there from the previous transactional run.
    how log files are created and what is meant of using transaction and not using transaction in db environment and what are this db files db.001,db.002,_db.003,_db.004,__db.005 and log files like log.0000000001Have you reviewed the basic documentations references for Berkeley DB Core?
    - Berkeley DB Programmer's Reference Guide
    in particular sections: The Berkeley DB products, Shared memory regions, Chapter 11. Berkeley DB Transactional Data Store Applications, Chapter 17. The Logging Subsystem.
    - Getting Started with Berkeley DB (Java API Guide) and Getting Started with Berkeley DB Transaction Processing (Java API Guide).
    If so, you would have had the answers to these questions; the __db.NNN files are the environment shared region files needed by the environment's subsystems (transaction, locking, logging, memory pool buffer, mutexes), and the log.MMMMMMMMMM are the log files needed for recoverability and created when running with transactions.
    --Andrei                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for

  • How can I check for references to previous server and remove them?

    I recently migrated several Win7 PC's off an old sbs2003 box to a new 2012 essentials server. All client data is stored on the server in a shared folder and that is mapped to the local PC's. Everything has been great, except we have noticed a delay o

  • Problem with opening query in Report Designer

    i am not able to open any quey in report desingner and facing RFc connection failed RSOBOLAP . is there any solution to solve the problem.

  • Excel output display error

    Hi Experts, I have an Standard Report Materials Account Distribution Report that I have converted to XML report (excel output). The report shows correct values for about 4100 lines. After that, I find that the merged cells have split and hence partia

  • Programming Analog Input Registers for MSeries NI-6221

    I am trying to understand the Preliminary M Series Register Map in order to correctly setup and acquire data from the Analog Input channels of my PCX-6221 card. I have been able to figure out the DIO locations and use them but I am having trouble und

  • Photo effects in Garageband

    Is there a way to dissolve between photos in a Garageband podcast? Or is a cut between photos the only way to show the photos? I'm matching photos to a pre-recorded narration and can't create a slideshow first.