Static Singleton instance reference gets cleaned memory!

OK, it's one of the strangest things I've ever seen.

I am currently working on a project where I use a singleton like this:

public class SingletonExample {  private static SingletonExample instance; private Vector listeners; private PhoneListener phoneListener;

  private SingletonExample(){       listeners = new Vector();     phoneListener = new PhoneListenerImpl();  }

  public static synchronized SingletonExample getInstance(){        if(instance == null){         instance = new SingletonExample();        }     return instance;  }

  public synchronized void addListener(SomeListener listener){      if(listener != null){         synchronized(listeners){              listeners.addElement(listener);               if(listeners.size() == 1){                    Phone.addPhoneListener(phoneListener);                }         }                 } }

  public synchronized void removeListener(SomeListener listener){       if(listener != null){         synchronized(listeners){              if(listeners.contains(listener)){                 listeners.removeElement(listener);                }                 if(listeners.isEmpty()){                  Phone.removePhoneListener(phoneListener);             }         }                 } }

  private void reportListeners(){       synchronized(listeners){          int sz = listeners.size();            for(int i = 0; i < sz; i++){               final SomeListener sl = (SomeListener) listeners.elementAt(i);                new Thread(){                 public void run(){                        sl.onListenerReported();                  }             }.start();            }     } }

  private class PhoneListenerImpl implements PhoneListener {        public void callAdded(int arg0) {}

      public void callAnswered(int arg0) {}

       public void callConferenceCallEstablished(int arg0) {}

      public void callConnected(int arg0) {     }

       public void callDirectConnectConnected(int arg0) {}

     public void callDirectConnectDisconnected(int arg0) {}

      public void callDisconnected(int arg0) {          reportListeners();            }

       public void callEndedByUser(int arg0) {           reportListeners();                }

       public void callFailed(int arg0, int arg1) {          reportListeners();                    }

       public void callHeld(int callId) {}

     public void callIncoming(int callId) {}

     public void callInitiated(int callid) {}

        public void callRemoved(int callId) {}

      public void callResumed(int callId) {}

      public void callWaiting(int callid) {}

      public void conferenceCallDisconnected(int callId) {} }}

(Not the best singleton, but very safe and is the one I usually use).

Want to-be-singleton class contains a collection of the listener (I have not included SomeListener interface, but it is very simple, only an onListenerReported of the method). Also contains an instance of PhoneListener. When a call is disconnected, the class of SingletonExample should report each listener on a new Thread.

Now the collections on static variables is subject to leaks memory, but this class is intended to contain only one or two listeners at a time, so there is not much. And as we are about to see, the static integer variable 'instance' is going to be garbage collected between "consecutive" calls to getInstance.

Now, I have a method like this, taken from a menu action:

public void someMethodFiredFromMenu() {  new Thread(){     public void run(){

          SomeListener listener = new SomeListener(){               public void onListenerReported() {                    System.out.println(">>>>>>> Call disconnected!");

                  //FIXME: Singleton static member is null at this point,                   // so it is constructed again!!!                  SingletonExample.getInstance().removeListener(this);

                  //Do other things here                                    }                                     };

          //First call to getInstance, static member is constructed as expected         SingletonExample.getInstance().addListener(listener);     } }.start();}

If test you it on a 4.7 Simulator I (BlackBerry 9530 Simulator, v4.7.0.75) you can see that the static variable singleton (named 'instance' within class SingletonExample) is collected between calls to someMethodFiredFromMenu.

It never happened to me before. Somehow, that there are two threads involved, the JAVA virtual machine (if we can call it ) determines that the variable is more accessible and collects, thus screwing my design.

Interesting things:

Make two consecutive getInstance calls in the same thread works.

Holding a last reference to the SingletonExample within the method of the menu and its use (even in different threads) also works.

* Note: I've changed a few names from my original code, so there are compilation errors, but at least you know what the code meant.

It is a feature of the BlackBerry JVM and what others have stumbled on before, including me.

The best way to summarize the problem is that a static is only a Singleton when the static object references are in the same instance of the Application.

Another way to say it is that each instance of the Application has its own set of static variables.

The problem here is that you code earphone is running an application, which will have a set of difference of static variables for your Application.

Here the best way to create a Singleton in a BlackBerry

http://supportforums.BlackBerry.com/T5/Java-development/create-a-singleton-using-the-RuntimeStore/TA...

That said, I would recommend that you avoid treatment on the earpiece - if you can only use global event to convey the information for your Application, then it can be handled in your Application and static object is a Singleton!

A bit off-topic and just because I'm here, but what's the point of the Thread in this treatment?

public void someMethodFiredFromMenu() {}
New Thread() {}
public void run() {}

SomeListener listener = new SomeListener() {}
public void onListenerReported() {}
System.out.println ("> call disconnected!");

FIXME: Singleton static member is NULL at this point,
Thus, it is built again!
SingletonExample.getInstance () .removeListener (this);
Do other things here
}
};

First call to getInstance static member is built as planned
SingletonExample.getInstance () .addListener (listener);
}
}. start();
}

Tags: BlackBerry Developers

Similar Questions

  • Problem has been detected and windows has been shutdown error STOP: 0x0000008E. Get the memory dump after you have installed the trial version of MS Project 2010.__space.

    Original title: problem has been detected and windows has been shut down. Get the memory dump after you have installed the trial version of MS Project 2010.__space.

    Computer Message: Check if you have enough disk space. If a driver is identified in the stop message, disable the driver or check with the manufacturer for driver updates. Try changing video cards.

    Check with your suppliers of material, updates the BIOS. Disable the BIOS memory options such as implementing caching or shading. If you need to use Safe Mode to remove or disable components, restart your computer, press F8 to start advance startup options, and then select Safe mode.

    Technical information: * STOP: 0x0000008E (0xC0000005, 0x8054556C, 0xADB78A98, 0x00000000)

    Beginning physical memory dump

    Total physical memory dump. Contact technical support for further assistance group.

    Hi fernandomventura,

    Step 1: Disconnect all external devices (printers, scanner, USB (universal serial bus) readers, etc...) Except the keyboard and mouse and then start.

    If this solves the problem, then add back devices at a time until you discover the piece of hardware causing the issue.  Then get any drivers\software update for the device.

    Step 2: Follow the steps mentioned in the articles below which deals with a similar question

     

    General troubleshooting for an error message that you receive randomly in Windows XP: "Stop 0x0000008E"-restore the system to achieve ".

    http://support.Microsoft.com/kb/945658/

    You receive a random "0x0000008E" error message on a blue screen in Windows XP

    http://support.Microsoft.com/kb/827663

    Thank you, and in what concerns:

    Ajay K

    Microsoft Answers Support Engineer

    Visit our Microsoft answers feedback Forum and let us know what you think.

  • Remember: if I delete records, do I get the memory they used?

    I have large files which I copied on my externalhard drive.  If I have SupprimerLa files, I get the memory back, they used.

    If you delete the original folders you copied, find you the hard disk space, called secondary memory.

    See you soon.

    Mick Murphy - Microsoft partner

  • How can I get more memory on my laptop?

    How can I get more memory on my laptop?

    Uh, buy it

    Care to be more specific?

  • I get virtual memory is low opinion.

    computer running slow

    How can I do things from here to free up the space/memory?

    I got this computer with Windows XP since 2004 & never really drained all the old programs / unused.

    I went to the Control Panel, add/remove programs and deleted what I know, that I don't use, but I don't want to spoil anything.

    Help! and thank you!

    Hello Tracy,.

    This means that you have little free disk space on your C volume that is limiting the scope of the size of the pagefgile can develop.

    What is the processor and RAM how much your computer have? Make a right-click on the icon my computer on your desktop and select properties for this information.

    Try Ctrl + Alt + Delete, select Task Manager, and then click the performance tab. Under Commit Charge, which is the Total, limit, and the pic?

    You can create more free space in C in carrying one of the measures suggested below.

    The default allocation for the restoration of the system is 12% on your C partition is more generous. I have them would be reduced by 700 MB. Make my computer right click on your icon, and select System Restore. Place the cursor on your C drive select settings but this time find the slider and drag it to the left until it shows 700 MB and output. When you get to the settings screen, click on apply and OK and leave.

    A flaw that might be useless which is for temporary internet files, especially if you keep no copies on the disk offline. Setting the default value is 3% of the walk. Depending on your attitude to copies offline, you could bring it to 1% or 2%. In Internet Explorer, select Tools, Internet Options, general, temporary Internet files, settings to make the change. At the same time, look at the number of days, the story stands.

    The default allocation for the basket is 10% of the disk. Change to 5%, which should be enough. In Windows Explorer hover over your Recycle Bin, right click and select Properties, Global and move the slider from 10% to 5%. However, try to let you become so complete that if it is complete and you delete a file by mistake it will bypass the Recycle Bin and have gone forever.

    If your drive is formatted as NTFS another potential gain arises with your operating system on your C drive. In the Windows directory of your C partition you will some uninstall files in your Windows folder in general: $NtServicePackUninstall$ and $NtUninstallKB282010$ etc. These files can be compressed or not compressed. If compressed text the name of the folder appears in blue. If these files are not compressed you can compress. Right-click on each folder and select Properties, general, advanced, and check the box before you compress contents to save disk space. On the general tab, you can see the winning amount by deducting the size on disk size. File compression is only an option on an NTFS formatted disk partition / partition.

    Select Start, all programs, accessories, System Tools, cleaning disk to emptying your trash, delete temporary Internet files and other selected options. I recommend also you click Other Options, System Restore and delete all but the last system restore point. Run Disk Defragmenter.

    Using the system restore option is most appropriate when your system is slow and you need to increase the free disk space on your C partition. If you have errors that could be solved by using the system restore to your system settings back to before the error occurred initially do not use this option.

    If more than one person uses the computer and they have their own user log you need to run Disk Cleanup in each user profile that you want to delete all the unwanted files.

    A better program of disk cleanup is cCleaner. Delete System Restore points may be important if you have little free disk space. The ability to delete them is one of the tools options. cCleaner comes with a registry tool. Do not use this tool as any registry cleaner could lead to the creation of very difficult to resolve system errors.

    http://www.CCleaner.com/download

    Kind regards

    Chauvet J.

  • Help! How to get more memory?

    My computer always indicates a not enough space on OS C.  Have done disk clean up, deleted files and programs, but said still is not enough memory.  What can I do else?  Please instruct me in layman's terms, as I am not the most computer.  Thanks in advance for any help.

    Space and memory are two different things.

    Space vs memory explanation

    When it comes to a computer, there are so many computer terms like MHz, RAM etc that people may find confusing, gigabytes. Having a better understanding of some of these terms can help you feel more comfortable using your computer and ultimately get more out of him.

    A lot of people I talk to seem to be apologetic about their lack of knowledge. It's too bad people feel this way. they shouldn't really. What I tell them is that, although they do not know as much as I do on computers, there is nothing wrong with that, and they probably know a lot of other things that I don't know much.

    What you need is someone who takes the time to explain things in a way that makes sense.

    A term many people confuse memory or RAM and hard disk storage space is. RAM stands for Random Access Memory (don't worry, you do not need to remind that!).

    It's a temporary workspace, the computer uses to get the job done, which gets emptied when the computer is turned off.

    Think of it as a work bench or table. You have a project that you are working on and do you your project on the bench and when you're done, you delete it off the coast.

    The disc is the main place of your computer uses to store information. It looks like a rectangular metal box containing a hard drive (as opposed to something like a CD player where you can remove the drive).

    It's a disc inside the drive that stores everything on your computer - each photo, each music file, every e-mail and every Word document. Not only that, but Windows or Mac OS X, the operating system that makes the computer run.

    To continue our analogy, think of it as a set of shelves where you store tools or materials for your project when you want to work on something, you choose the things you need on the shelves, put them on the bench and working on the project.

    It of like when you run a program; the computer to load the program from the hard disk in memory (the temporary workspace).

    So more shelves, plus you can store - that is to say programs more can you install, the more songs or photos or videos, you can save on your computer.

    Most people with a computer in the last years are tougher than they will ever use. Few people ever the charging, unless they hold a large number of large files such as audio files or images or video files in particular.

    A picture is worth a thousand words, they say. If it's true, video is worth at least 1 million words and files can be that much bigger!

    If someone tells you that you have need of more memory, or your computer gives you an error to be low on memory, this usually means that you don't have enough RAM. This can significantly slow down your computer.

    Consider the idea of bench again: If your bench is very small, you can't hold it need make your work, so you are constantly losing time move a piece of the project to the bench to make room for the next piece... If you really work at all.

    The RAM and disk space are measured with the same terms: bytes, kilobytes (KB), megabytes (MB), gigabytes (GB), with newer drives even being measured in tera-bytes (to). As the RAM and hard drives are measured in the same way, it is perhaps one of the reasons people are confusing the two terms.

    You don't need to understand exactly what these terms mean, but understand that each of them is essentially a thousand times larger than the previous. So a kilobyte is 1,000 times the size of a byte, a megabyte is 1000 times larger than a kilobyte, a gigabyte is thousand times later than that and so on.

    The reason you buy a computer, one that has a lot of RAM and two or three years respect and all of a sudden someone tells you that you don't have enough memory, because every year, size average programmes and the amount of memory they need, expands.

    It's as if the tools you use on your Workbench continue to grow each year in order to have afterwards get a larger bench.

    If your computer seems to work more slowly recently, or if you have had bizarre mistakes, it could be that you need to upgrade your memory. This is not always the source of these problems, but RAM is cheap these days and add to what your computer can add life to your Mac or PC.

    I hope that this clears up the meaning of these terms the basic computer for you and makes much more sense than before! To learn more about the RAM and memory, read related article that explains how RAM affects the speed of a computerand more.

    `~`

    http://www.Google.com/#gs_rn=18&gs_ri=psy-AB&CP=7&gs_id=q&XHR=t&q=page+file&es_nrs=true&PF=p&output=search&sclient=psy-AB&OQ=page+fi&gs_l=&PBX=1&BAV=on.2, or.r_qf. & bvm = bv.48572450, d.cGE & fp = d9f7c8d7788ea4ef & biw = 853 & bih = 561>

    http://www.Google.com/#gs_rn=18&gs_ri=psy-AB&PQ=page%20File&CP=17&gs_id=14&XHR=t&q=memory+management&es_nrs=true&PF=p&sclient=psy-AB&OQ=memory+management&gs_l=&PBX=1&BAV=on.2, or.r_qf. & bvm = bv.48572450, d.cGE & fp = d9f7c8d7788ea4ef & biw = 853 & bih = 561>

    `~`

    The time and date of this moment in California, the United States is 14:12

    Sunday, June 30, 2013
    The time Pacific daylight time (PDT)-0700 UTC
     
    UTC/GMT is 21:12 on Sunday, June 30, 2013
                
    Current weather conditions in Los Angeles

    Just92 ° F / 33 ° C
  • Keep getting a memory could not be written error with Acrobat Pro XI

    Hello

    Below is the error I keep seeing on my windows 7 Adobe Acrobat Pro XI enforcement machine. It happens with any PDF that I opened and when it pops up it force closes xi pro adobe acrobat and does not allow me to save all data before it happens. In general, it gives me 20 seconds before it closes so if I am fast enough I could save it, but it does every 5 minutes or more.

    memory error.png

    Things I've tried...

    1 tried to use the cleaning of adobe tool to uninstall acrobat adobe pro xi completely from the computer, rebooted, reinstalled (same error at the same place)

    2. tried using forefront endpoint protection for not full system scan (what we use in our company) - no viruses (same error at the same place)

    3 tried to delete the user profile that has the question on our machine of the company, the addition of a new blank profile with acrobat (same error at the same place)

    4. I tried to reinstall windows (wipe everything) and reinstall acrobat (same error at the same place)

    5 tried to run memtest for my RAM and RAM integrated test tool, no error on RAM (same error even location)

    6. replace the RAM and motherboard in case there was a problem of memory onboard (same error even location)

    7. now, I gave the user a ready computer, same configuration and it works fine. No other program gives this error, but Adobe Acrobat Pro XI, and now I have a second user with a new laptop Dell get this error at the same place.

    We have a lot of users on the site using Acrobat if it was only 2 of a possible 3 k users having this same exact error, so don't know why it does on 2 completely different computer types. Any suggestions would be most useful at that time I tried registry fixes, changes to "memory could not be read error" but that does not help that I found on this forum.

    Thank you!

    -Troy

    Hi Troy,

    I see that you have completed the major part of the basis of troubleshooting.

    Please contact support for more advanced troubleshooting.

    Contact the customer service

    Kind regards
    Rave

  • Satellite U300 - I get BSOD memory dump problem

    Hello

    Can anyone help? I got my U300 for a week and the first time I turned it on it had problems in Vista Setup process.
    He seemed to recover. I now get the dreaded blue screen with dump of memory on this subject, saying I have to restart the pc.

    Then it takes ages to restart because the hard drive light blinks and then turns off.

    Do you think I should contact Toshiba I installed virtually any software on it? or would u reinstalled Windows?

    See you soon
    Becks

    First, you must use the Toshiba Recovery CD to reinstall the OS in this Satellite U300.
    Eventually it s something wrong with the OS installed and the new facility could help to solve this problem.

    But if the same thing will happen after the installation of the new operating system, then you should contact the ASP in your country for a control of the laptop.

    Best regards

  • Satellite M200 - cannot get card memory SD camera to work

    Hello.

    I have a Toshiba Satellite M200 and tried to download photos from a memory card from my digital camera on it using the multimedia slot on the front of the laptop, however nothing happens when I put the memory card.

    It is a SanDisk Ultra II 2. 0 GB, and I tried to look on the user manual to find if the media slot will take this card but can't seem to find anything - even impossible to find the manual on this Web site.

    Do I need software for this multimedia property work?

    If Yes, where can I get a? Thank you.

    Can you please tell us the name of the full model of your laptop?
    I checked the European Toshiba support page and this model of laptop is not here but on support US page it has listed two portable Satellite M200.

    Please check under http://www.csd.toshiba.com/cgi-bin/tais/support/jsp/home.jsp?nav=Download#

    If your laptop model is listed you will find s manual user with the exact specification for laptop and the list of all supported cards that can be used with multimedia slot.

    Good luck!

  • Satellite M70 - where to get the memory expansion

    Hi all

    It's my first time here and I was hoping someone could help me please.

    My brother has a Satellite M70 which currently has 1 GB of memory and that he was willing to expand this to 2 GB.
    Does anyone know where we can get parts to do this in Australia, site Web from Toshiba in Aus is not direct sales or online?

    The technical info I have, it seems that an expansion of 1 GB card is KTT533D2/1GI part number, it seems okay for those of you who may know?

    Don't really know much about it so hope I don't sound completely stupid!

    Thank you
    June

    Hello

    Have a look here:
    http://www.orcalogic.co.UK/ASP/ProdType.asp?ProdType=19229&ft=m&St=3

    You will find compatible memory modules for Sat M70.

    According to this page, you can use DDR2 533 MHz (PC2-4200) 200 - PIN SODIMM.
    Usually (but not always) it s any manufacturer is.
    Very important are the specifications of the module

    I recommend that you are looking for a DDR2 533 MHz (PC2-4200) 200 - PIN SODIMM and I m you will find some good deals online.

  • I don't have the money to buy more ram, how to remove programs to get more memory and how do I know which programs remove

    I need of more memory, I can't afford to buy it, how to remove stuff to create more memory and how do I know what programs are ok to remove

    I think you're confusing terms and certainly confuse us.

    RAM/memory (they are identical) is the memory on the computer that is used by programs running as a temporary store for data.  How to reduce the amount of memory used is to close unnecessary programs or does not work as much.  for example close the browser and your e-mail so that the execution of Word program.  You do not need to uninstall programs, run just not, to save memory.

    IF you talk about not having enough disk space to store your programs and data, then the way to increase the free space on the disc IS to uninstall unnecessary programs - only you can decide what programs you don't need.  One way to increase disk space is to make sure you have emptied your Recycle Bin to delete the old data files, you don't want to, and uninstall programs.

    You need to tell us exactly what error messages you get so that we can determine what your problem is.

  • How can I get more memory? Should I go through Dell (it is a Dell computer)? I get the message too low virtual memory.

    I get the message "out of virtual memory"... In order to buy more memory, can I contact Dell for this (there is a Dell computer)?

    "Out of virtual memory" has nothing to do with the amount of physical RAM you have installed.  These errors are caused by incompatible programs, too little free capacity available on the hard drive, correctly configured virtual memory (you set it so Windows automatically manages) or sometimes even by a severely fragmented hard disk partition.

    Virtual memory in Windows Xp too low WARNING

    http://www.troublefixers.com/fix-virtual-memory-too-low-warning-trouble-in-Win-XP/

    TIPS COMPUTER virtual memory insufficient attention Trouble in win xp and vista

    http://www.tricksystem.com/2009/01/virtual-memory-too-low-warning-trouble.html

    But, if you decide you want to increase your RAM anyway, memory Crucial (www.crucial.com) website has a database to help find the right RAM for your specific brand and model computer or the motherboard.  (By the way, Crucial is the only company I have ever buy RAM.)  I've never been disappointed.)  And it will be significantly cheaper than buying at Dell.

  • Reference Dell upgrade memory T610

    I have Dell T610 with a CPU E5506 server. I want to get out all of the memory from the server and install the new memory 4 grade 8Gb 2Rx4 RDIMMS DDR3 1333 MHz LV (Snpp9rn2c / 8g).

    Will be ok? I got 32GB? Assorted memory work correctly with CPU E5506?

    The 8 GB memory you bought is a low voltage given double revenu3 type double row of double error correction in modules of memory in line with Government (on the address lines?). They are compatible with your T610 and should work without problems (assuming that there are no unknown hardware failure).

    What slots place you the RDIMMs will depend on you specify settings of the BIOS memory mode. If I understand correctly, this in turn can affect the speed of memory.

    I would 1st set BIOS memory mode 'Advanced ECC' and place your RDIMS in the 4 closest slots of CPU1 leaving farthest 2 empty slots. Then I would run a memory benchmark to check performance.

    You could also try changing the mode memory BIOS to "Optimized" and place the RDIMMS 3 white slots with 4th in the black slot more away from the CPU (marked A4). Then run a cue memory point and compare with the above configuration.

    Each configuration should give you 32 GB.

    You don't mention this type, the size or the number of DIMMs you had previously installed in your system, it is therefore impossible to tell if they can be reused or how. But since you mention that you replace them, I guess that's irrelevant anyway. However, if your old memory was UDIMM type (without buffer only = no records on the data lines), it's safe to say that you can not mix with of the UDIMM RDIMMS. If you old memory was of RDIMMS you can reuse them (but if they are not the type of low voltage, you will get the benefit of low voltage of your new memory because it will work under tension will use and therefore consume more power than would otherwise be the case).

    Good luck.

  • How can I get free memory in my pc

    I have no money now to get memory and some of the things on my pc that I can't remove this moment how can I memory for free please a little help

    Try to run a disk cleanup

    Go to start and type disk cleanup

  • Question of cleaning memory of blackBerry Smartphones

    Hi all

    While not not new to BB, I'm new on my Storm 9530. That being said, I have a question about the memory cleaning option on my BB Storm. Should I allow it and let it run all the time or should I just use if necessary. Any help will be appreciated. Thank you

    I leave it on on my Storm. I know that the manual inside the applications folder can actually reduce the amount of RAM free. I had 32MB or so free, ran the Manual vacuum and ended up with about 28 MB.

Maybe you are looking for

  • drop between mid-2009 and IOS device does not

    Mid 2009 Macbook Pro running El Capitan. Bluetooth and wifi on. When I opened Airdrop I see only the symbol of release with message "drop we will share you instantly... to share with someone using a Mac, ask them to go to Airdrop in the Finder. I don

  • Satellite A100-049 Modem SM2173ALD07 64 Bit Vista driver needed

    I'm looking for drivers for Vista 64 bit for the: SM2173ALD07 - software modem Dial-up I have a laptop Toshiba Satellite A100-049 and that you can find the 32-bit drivers. I managed to find 64-bit drivers for pretty much everything (No. with Toshiba)

  • Can a laptop Lenovo ThinkPad T410 have a NVIDIA GeForce graphics card?

    I was just wondering can a Lenovo ThinkPad T410 laptop hold a NVIDIA GeForce graphics card? I want to change my current graphics card and I found a good graphics card.

  • Problems of mail storm blackBerry Smartphones

    Had a storm.  Have two e-mail accounts.  A yahoo account and my work.  The phone will not accept a preset "sent to help.  This means that one of the emails always send to the wrong account.  I have the ability to select what email I want to send him,

  • Error creating surrogate key

    Hi am in jdeveloper 11.1.1.7.0 trying to create the surrogate key, that's what I did, I'm going to my entity and create a new attribute with a type of DBSequence and I go to VO I add this new attribute, now when I test my BC am getting error that the