Please explain soft/weak references to me!

What I would like to do is have following class:
abstract class ImageContainer
  private Image img;
  public Image getImage()
    if (img==null)
      renderImage();
    return img;   
  public void lowMemory()
     img=null;
     System.gc();
  abstract protected void renderImage();
}I think that you get my point, but this doesn't really work, since there's noplace where from call lowMemory() (and I mean low RAM memory, not low swapping memory, since this is to remove swapping during gameplay). I need somehow to use soft references or something like that so I was wondering if you could point me to right direction... I was unable to understand completily the API for package java.lang.ref

abstract class ImageContainer
private SoftReference imgRef = new SoftReference();
public Image getImage()
   Image img = (Image)imgRef.get();
   if (img==null)
      img = renderImage();
      imgRef = new SoftReference(img);
   return img;
abstract protected Image renderImage();
}Reference objects "wrap" a regular hard reference, passed into the constructor. The "get" method returns that reference, or null if the object has been collected. (After a GC cycle for WeakReference, after a low-memory condition for SoftReference.) Therefore, upon fetch, call "get" on the reference class and check for null. If null, recreate and create a new reference class instance. Return the object either re-fetched or just created.

Similar Messages

  • Soft/Weak References: rule of thumbs?

    After reading <a target="extern" href="http://java.sun.com/developer/technicalArticles/ALT/RefObj/index.html">Reference Objects and Garbage Collection</a> i browsed my code and replaced my listener containers with versions that store WeakReference objects. The main idea is to avoid memory leaks by storing references to objects that are not needed anymore (the listener container is the only strong reference left).
    Another rule is to use SoftReferences for caches. But I haven't figured out a good way of implementing it (for caches that fill itself with one single SQL statement).
    Are there any other examples where it's good advice to use Soft/Weak References?

    For listeners, you have to make sure that the listener object is hard referenced - which is usually the case. After you release the listener object from the main application/object/thread, because it's finished or you don't need it anymore, the listener holder should not hold on to such references to avoid OutOfMemoryExceptions. Of course, the best way is always to unregister a listener, but unfortunately, we're not living in a perfect world. No listener is forced to unregister, they can simple forget to unregister. For this reason, it's better to tell the listener: if you register yourself, you should know that you are just referenced via WeakReferences. If the listener suddenly doesn't get listener events, this is a coding error which can be traced and fixed. But if a listener forgets to unregister itself, the resulting memory bloat is much harder to trace.
    SQL table caches are difficult. On one hand you want to cache the data, on the other, you want to free this cache memory (temporarily) for more important memory usage. It's always a trade off between 2 advantages. If performance is not the big issue, but you get OutOfMemoryExceptions, then this is critical for the application to continue working. Better a little slower than not at all ... ;-)

  • How strong ,soft ,weak ,phantom references are used in garbage collection

    Hi
    to all here.I have doubt that how garbage collection is deciding to cleaning up heap , and what are the roles of strong , soft , weak and phantom reference in garbage collection, i went throgh sun's java docs but i couldn't get any clear idea about those , please can anyone explain me with nice examples for which i will be really thankful.

    See:
    http://java.sun.com/developer/technicalArticles/ALT/RefObj/

  • Are weak references cleared with soft ones?

    Suppose a program holds both weak and soft references to an object X. Suppose the virtual machine clears all the soft references at once, making X weakly reachable. Is the virtual machine guaranteed to clear all the weak references next before normal execution resumes?
    I ask because I am setting up an automatic interning system for immutable objects of a certain class that will guarantee that at most one object of a given value is reachable by the rest of the program at one time but will allow objects to be garbage collected if necessary. I need to decide what reference object(s) to keep to each interned object. If I keep only a weak reference, objects will be discarded at the whim of the virtual machine; I would prefer to keep them around longer so they don't have to be recreated so many times. If I keep only a soft reference, I am concerned that another part of the program might keep a weak reference. If the answer to my question above is "no", the soft reference could be cleared and the interning system could create a second object with the same value while the first is still accessible via the weak reference. It seems safest to keep both a soft reference and a weak reference and only recreate the object if the weak reference has been cleared.

    Softs hang around until memory needs dictate theygo.
    In my experience (Apple's 1.4 VM) this appears to be
    as soon as GC is run, making them effectively
    useless. Maybe VMs have improved.Not in my experience (Sun 1.4 VM). Soft references hang around forever. I had to stuff my class with bloat to make the instance larger, then change the VM heap size to get it to start collecting my soft references. Whereas the weak references are dumped ASAP. Inside scoop has it that finalizers will delay object collection a bit so be careful of that.
    Also the only guarantee is that soft is cleared before weak when they refer to the same object. in my experience weak references go quickly. Like at the first GC when they are weak. You can not depend on any timing with respect to when the weak will be cleared. I don't think the spec even guarantees that soft will be enqueued before weak. Im not sure on that point.

  • IterateOverReachableObjects and soft/weak/phantom references

    Hi,
    what are soft/weak/phantom references for the JVM TI call IterateOverReachableObjects? Are those reference-objects
    1. ... "normal" objects having references and beeing traversed by this function
    (OR)
    2. ... interpreted as references with hiding the object nature
    (OR)
    3. ... ignored as they are ignored by the GC?
    Thanks,
    Robert

    The reference_kind with JVMTI_REFERENCE_FIELD, the referrer_tag will be the value of the tagged Reference instance, and the referrer_index will be the index of the "referent" field. It is this field that is treated in a special way by the GC.

  • Garbage Collection Weak References

    Can someone please explain to me the point of Weak References.
    here is what i understand
    // we have a strong reference object
    String strong = new String("i am a strong reference");
    // we create a weak reference object
    Reference wr = new WeakReference(strong);
    Now what i have understood from my readings is that now when strong dereferences the object that was initially created the garbage collector deallocates the memory for that item.
    but what is the point of a WeakReference?

    This might be useful for you.
    http://java.sun.com/developer/technicalArticles/ALT/RefObj/

  • Cannot create weak reference to 'classobj' object

    I am trying to run the python Script in a C# program using Iron Python I am getting this type of Error
    cannot create weak reference to 'classobj' object
    I am using this code for running the python code
    var ironPythonRuntime = Python.CreateRuntime();
    try
    dynamic loadPython = ironPythonRuntime.UseFile("Program.py");
    catch (Exception ex)
    Console.WriteLine(ex.Message);

    Hi Mahesh,
    About IronPython issue, It's third-party product.  Please redirect to IronPython forum.  The link as below.
    https://ironpython.codeplex.com/workitem/list/basic
    After search this error,
    this thread tells me.
    Try to use virtualenv. It is used to separate many instances of python and it's libraries - you can have as many virtual environments as possible: python 2.5 , 2.6 , 2.7, whatever - with any combinations of libraries - so you can have for example five
    python 2.6 instances with different sets of libraries configured.
    By the way, here is also a blog talking about
    Running IronPython Scripts from a C# 4.0 Program
    Now I will move your thread to "off-topic" forum. Thanks for your understanding.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Can you please explain in detail about the T-Code SM59

    Can you please explain in detail about the T-Code SM59

    Hi Raja,
    detailed explanation is already available over help.sap.com.
    For your ready reference check below links
    http://help.sap.com/saphelp_spm21_bw/helpdata/en/57/898009a859493a8bce56caaf0f8e13/frameset.htm
    http://help.sap.com/saphelp_webas610/helpdata/en/da/11df3a9b10355ae10000000a11405a/frameset.htm
    http://help.sap.com/saphelp_snc70/helpdata/en/3f/7ffb40ef74f923e10000000a155106/frameset.htm
    Regards
    Jitender

  • Enqueue and Dequeue consept----Please explain urgent

    hi all,
    i want to use sap locking mechanisn (Enqueue and dequeue consept) while updating database table....please explain how to use this while updating a database table.
    Thanks in advance
    Nandha kumar

    Nandha,
    Good document on this concept..
      Activating a lock object in the ABAP Dictionary automatically creates function modules for setting (ENQUEUE_<lock object name>) and releasing (DEQUEUE_<lock object name>) locks.
    The generated function modules are automatically assigned to function groups. You should not change these function modules and their assignment to function groups since the function modules are generated again each time the lock object is activated.
    Never transport the function groups, which contain the automatically generated function modules. The generated function modules of a lock object could reside in a different function group in the target system. Always transport the lock objects. When a lock object is activated in the target system, the function modules are generated again and correctly assigned to function groups.
    Parameters of the Function Modules
    Field Names of the Lock Object
    The keys to be locked must be passed here.
    A further parameter X_<field> that defines the lock behavior when the initial value is passed exists for every lock field <field>. If the initial value is assigned to <field> and X_<field>, then a generic lock is initialized with respect to <field>. If <field> is assigned the initial value and X_<field> is defined as X, the lock is set with exactly the initial value of <field>.
    Parameters for Passing Locks to the Update Program
    A lock is generally removed at the end of the transaction or when the corresponding DEQUEUE function module is called. However, this is not the case if the transaction has called update routines. In this case a parameter must check that the lock has been removed.
    Parameter _SCOPE controls how the lock or lock release is passed to the update program (see The Owner Concept for Locks). You have the following options:
    _SCOPE = 1: Locks and lock releases are not passed to the update program. The lock is removed when the transaction is ended.
    _SCOPE = 2: The lock or lock release is passed to the update program. The update program is responsible for removing the lock. The interactive program with which the lock was requested no longer has an influence on the lock behavior. This is the standard setting for the ENQUEUE function module.
    _SCOPE = 3: The lock or lock release is also passed to the update program. The lock must be removed in both the interactive program and in the update program. This is the standard setting for the DEQUEUE function module.
    Parameters for Lock Mode
    A parameter MODE_<TAB> exists for each base table TAB of the lock object. The lock mode for this base table can be set dynamically with this parameter. Valid values for this parameter are S (shared), E (exclusive) and X (exclusive but not cumulative).
    The lock mode specified when the lock object for the table is created is the default value for this parameter. This default value can however be overridden as required when the function module is called.
    If a lock set with a lock mode is to be removed by calling the DEQUEUE function module, this call must have the same value for the parameter MODE_<TAB>.
    Controlling Lock Transmission
    Parameter _COLLECT controls whether the lock request or lock release should be performed directly or whether it should first be written to the local lock container. This parameter can have the following values:
    Initial value: The lock request or lock release is sent directly to the lock server.
    X : The lock request or lock release is placed in the local lock container. The lock requests and lock releases collected in this lock container can then be sent to the lock server at a later time as a group by calling the function module FLUSH_ENQUEUE.
    Behavior for Lock Conflicts (ENQUEUE only)
    The ENQUEUE function module also has the parameter _WAIT. This parameter determines the lock behavior when there is a lock conflict.
    You have the following options:
    Initial value: If a lock attempt fails because there is a competing lock, the exception FOREIGN_LOCK is triggered.
    X : If a lock attempt fails because there is a competing lock, the lock attempt is repeated after waiting for a certain time. The exception FOREIGN_LOCK is triggered only if a certain time limit has elapsed since the first lock attempt. The waiting time and the time limit are defined by profile parameters.
    Controlling Deletion of the Lock Entry (DEQUEUE only)
    The DEQUEUE function module also has the parameter _SYNCHRON.
    If X is passed, the DEQUEUE function waits until the entry has been removed from the lock table. Otherwise it is deleted asynchronously, that is, if the lock table of the system is read directly after the lock is removed, the entry in the lock table may still exist.
    Exceptions of the ENQUEUE Function Module
    FOREIGN_LOCK: A competing lock already exists. You can find out the name of the user holding the lock by looking at system variable SY-MSGV1.
    SYSTEM_FAILURE: This exception is triggered when the lock server reports that a problem occurred while setting the lock. In this case, the lock could not be set.
    If the exceptions are not processed by the calling program itself, appropriate messages are issued for all exceptions.
    Reference Fields for RFC-Enabled Lock Objects
    The type of an RFC-enabled function module must be completely defined. The parameters of the generated function module therefore have the following reference fields for RFC-enabled lock objects:
    Parameters
    Reference fields
    X_<field name>
    DDENQ_LIKE-XPARFLAG
    _WAIT
    DDENQ_LIKE-WAITFLAG
    _SCOPE
    DDENQ_LIKE-SCOPE
    _SYNCHRON
    DDENQ_LIKE-SYNCHRON
    Pls. reward if useful

  • HT2493 Could someone please explain colour tags?

    I do not understand the use of colour tags on my Macbook air. Could someone please explain?

    The colours are incidental. They are NOT labels any more. You will be frustrated if you try to use Tags to visually find your files.
    The advantages of tags are this: you can add as many tags to a file as you like. They provide additional metadata so that you can query your file system. In a typical hierarchical file sytem (folders, subfolder), a file can only be in one place (unless you use aliases).
    If I have "Cheeses > France > Soft" as my folders, I can put all the French soft cheese into one folder. But all the English soft cheese are in England > Soft. So what if I want to list ALL the soft cheeses, not just the ones from France? By tagging all the files with "Soft", I can then click on the Tag Smart Folder and list the soft cheeses in both countries' folders all at once.
    If used creatively, you could have ALL the files in your Documents folder in one big heap, and then only view subsets of them according to their Tags. Tags represents a complete alternative to using folders to sort your files.
    In a sense, a subfolder is simply a Tag in a tree-like structure.
    So, instead of trying to visually find some files in a list using coloured labels, you can now query the file system by creating Smart Folders that give you a list of files that match your query: files with Tag X, in folder Y, of type PDF, bigger than 2 MB, containing the word "trumpet".
    Visually scouring a folder for files is not as efficient as directly querying the system, even if it is engrained and familiar.

  • Hi there, i have Q i have excel file it need to be block with password. Could you please explain how i make password protect to Excel document

    Hi there,
    i have Q i have excel file it need to be block with password. Could you please explain how i make password protect to Excel document
    Thanks

    On the File menu, click Save As.
    On the Tools menu, click General Options.
    Do either or both of the following:
    If you want users to enter a password before they can view the workbook, type a password in the Password to open box, and then click OK.
    If you want users to enter a password before they can save changes to the workbook, type a password in the Password to modify box.
    NOTE   Unlike passwords you specify in the Password to open box, passwords you specify in the Password to modify box are not encrypted. These passwords are only meant to give specific users permission to modify workbook data. For optimal password security, it's best to assign both passwords. An encrypted password to access the workbook, and one to provide specific users with permission to modify its content. IMPORTANT   Use strong passwords that combine uppercase and lowercase letters, numbers, and symbols. Weak passwords don't mix these elements. Strong password: Y6dh!et5. Weak password: House27. Use a strong password that you can remember so that you don't have to write it down.
    If you want to use a different encryption type, click Advanced, click the type you want in the Choose an encryption type list, and then click OK.
    If needed, specify the number of characters you want in the Choose a key length box.
    NOTE   Document property encryption is enabled by default for most encryption types and providers. It prevents unauthorized users from viewing summary and custom file properties (such as the author or any custom file information) in theProperties dialog box. When users right-click the password-protected file, and then click Properties, information won't be available on the Summary tab and Customtab. Authorized users, however, can open the file and view all file properties (Filemenu, Properties command). To disable document property encryption, clear theEncrypt document properties check box.
    Click OK.
    When prompted, retype your passwords to confirm them.
    Click Save.
    If prompted, click Yes to replace the existing workbook.
    NOTE   You can also secure a workbook with a password on the Security tab of the Options dialog box (Tools menu, Options command).

  • In our enterprise MPLS network we are using 192.168.20.0/24 subnet, in this subnet we have not assigned the IP 192.168.20.200/30 & 204/30, But still these subnets are reachable . Are these NNI IP ...Please explain.

    In our enterprise MPLS network we are using 192.168.20.0/24 subnet, in this subnet we have not assigned the IP 192.168.20.200/30 & 204/30, But still these subnets are reachable . Are these NNI IP ...Please explain.

    I have checked with ISP, there response is like below:
    Those are the NNI to GBNET IPs for Dominican Republic. They are Network IPs. You should be able to ping them-that means they are working.
    WANRT01#show  ip route | include 192.168.20.20
    B        192.168.20.200/30 [20/0] via 192.168.20.226, 02:18:29
    B        192.168.20.204/30 [20/0] via 192.168.20.226, 02:18:29
    Here its shows from any of our MPLS site we are able to trace the IP and it seems like, 192.168.20.204/30 is one more site but in actual its not.
    INMUMWANRT01#ping 192.168.20.205
    Type escape sequence to abort.
    Sending 5, 100-byte ICMP Echos to 192.168.20.205, timeout is 2 seconds:
    Success rate is 100 percent (5/5), round-trip min/avg/max = 224/232/260 ms
    INMUMWANRT01#trace              
    INMUMWANRT01#traceroute 192.168.20.205
    Type escape sequence to abort.
    Tracing the route to 192.168.20.205
    VRF info: (vrf in name/id, vrf out name/id)
      1 192.168.20.226 24 msec 24 msec 24 msec
      2 192.168.20.206 [AS 8035] 232 msec 232 msec 252 msec
      3 192.168.20.205 [AS 8035] 224 msec 224 msec *

  • Please explain me how I can use Form feed(\f) and Carriage return(\r)

    what is Form feed(\f) and Carriage return(\r)?
    Please explain to me.
    Thank you.

    These control characters aren't used much these days except that if you example a Windows or MSDOS text file in a binary editor you'll find each line ends with "\r\n". However when reading or writing text through classes these carriage returns will be added and removed automatically so your program doesn't see them.
    The controlls date back to teletype machines which operated rather like typewriters. Cariage return, as it's name implied, caused the print head to move back to the start of the line, line feed advanced a line (without, necessarilly, returning the carriage) and formfeed skipped to the next page.
    Newline on these machines was always "return, linefeed" because executing the carriage return on these machine could take too long. The early machines had only a single character buffer so that they had to executed the characters as quickly as they arrived. So doing the linefeed after the carriage return gave the carriage more time to return. On some teletypes if you did "linefeed, return" then the first character of the new line would often be printed somewhere in the middle of the line.
    This is the origin of the MSDOS/Windows end of line sequence.
    Many printers will still respect formfeed if printing is direct. Some will take carriage return without linefeed to allow you to start again overprinting the same line.
    However printing, these days, is seldom direct but done in bitmap form.

  • Please explain me, how to remove an usb stick or memory chip? With experiences only in pc:s, I do not find on my first apple e.g. MacBook Air a solution. Until now I have succeeded to destroy one chip full of photos and - there's no life more in the port.

    Please explain me, how to remove an usb stick or memory chip? With experiences only in pc:s, I do not find on my first apple e.g. MacBook Air a solution. Until now I have succeeded to destroy one chip full of photos and - there's no life more in the port...
    Someone told me just to remove the chip in clicking it to the trash can and voilá - it would be done. But as I did so, on the screen appeared a text which let me know, that that way had been the wrong one...
    I should have clicked Finder plus something.... which I do not now remember but which was then not found behind the Finder.
    So please would someone be so kind and tell me, where I can find explanations for the most simple functions. The manual I got does not include a clue.
    Thank you!

    First make sure that no application is using or has open any files on the disk. Then:
    Click and drag the disk icon on the desktop to the trash. Wait for the system to recognize the action, and the icon should disappear from the desktop. It is then safe to remove the device.
    Alternatively, you can secondary click on the disk icon, and then primary click "Eject (name of disk)". Wait for the icon to disappear off the desktop, and then it is safe to remove the drive.
    Here is a detailed help document on the subject.
    http://docs.info.apple.com/article.html?path=Mac/10.7/en/mchlp1056.html

  • Hi any one please explain background job scheduling

    Hi any one please explain background job scheduling . Good answer can be rewarded.
    Thanks

    Background jobs are pgms that are scheduled to be run in the Background without user interaction. So this can be done only for Type 1(executable) Program and not for Module-Pool Programs. Typically, a variant is defined and the pgm is run using the same.
    The transaction code is sm36 -Define Background job. Using the Start Condition tab you can define when you want the job to run (specific time or if it has to follow after a particular job is done etc.,) Using the Step tab you can assign the pgm name and variant.
    After the job is scheduled, you can check the status in sm37, along with the Job log and Spool.
    For more info:
    http://help.sap.com/saphelp_bw30b/helpdata/en/c4/3a7f87505211d189550000e829fbbd/content.htm

Maybe you are looking for

  • The invocation resulted in an error: java.util.NoSuchElementException

    I am trying to implement sftp protcol for oracle service bus using business service. While invocation it is throwing "The invocation resulted in an error: java.util.NoSuchElementException" error. Does any one know the reason for it?

  • Issue with List Files option in FTP Adapter-

    Hi All, I am getting the following error when I am using the list files option inside FTP adapter. The soa Version I am using is 11.1.1.5 Exception occured when binding was invoked. Exception occured during invocation of JCA binding: "JCA Binding exe

  • Sounds not working after 10.7.3 update

    After the update my mail, popup, system sounds aren't all working. Also some are now mixed up. The sounds are listed in the system prefs/sounds but they aren't working when needed. Anyone have any suggestions? thanks.

  • Approval step without capacity ad hoc

    Hi, In some workflows for some users we get the error message when we want to previsualize the approval levels of a Shopping Cart: "Approval step without capacity ad hoc, prevision impossible" What is the reason for this error message and how to corr

  • All in One Printers

    I have a Photosmart Premium C309a printer on Windows 7. I have just purchased an Ipad which needs "Air Print". My printer does not support Air Print, so it looks like I will need to purchase a new one. I need an all in one that has WiFi, Scanning, Co