SoftReference/PhantomReference idioms?

Hi all. I'm finding myself needing to use SoftReferences to implement a memory cache.
The trick is that I need to know when each object is garbage collected; I will serialize it to persistent storage and then deserialize it if/when it's needed later. In this case, the cost of recreating the object from scratch is sufficiently high that this approach makes more sense.
Since I know other fellow travellers have surely trod this road before, is there a well-known idiom (dare I say design pattern?) for this?
One option is to handle the serialization in the object's finalize() method. Are there any reasons not to do it that way (that's the direction I'm headed right now).
Alternatively, I suppose I could also create a phantom reference as well, but even though I've read Bill Venner's chapter and Monica Pawlan's technical article (both excellent, by the way), it's not clear to me how that would be constructed. I need to the soft reference so that the JVM GC's the object when needed, but I need the phantom reference to get to the object before it's cleared.
Actually, I was sort of surprised that when you associate a reference queue with a SoftReference, when you remove() the SoftReference from the queue, the pointer to the referent is already cleared. I don't really see what the use would be of a reference queue with anything but a phantom reference.
Any suggestions, pointers, tips, etc would be greatly appreciated. Thanks.

Well, it looks like I'm just talking to myself here, but I thought I'd relay what I discovered in tackling this problem.
First, given the availability of Reference objects I don't think finalizers are the way to go. Other sources I've read seem to confirm this. The main issue for me is that serializing & saving the object to backing store is a non-trivial task, and it seems that by the time the finalizer is called, the JVM could already be in a memory-constrained situation.
The approach I've taken is to save a copy of the object to backing store fairly early on in its life, so that when the GC wants to reclaim it, there's nothing that needs to be done.
Works like a charm.

Similar Messages

  • Como alterar o idioma do Thunderbird?

    Depois de fazer a atualização do Thunderbird para a 31.2.0, verifiquei que alguns itens do Thunderbird ficaram em Inglês, gostaria de saber como fazer ficar todo em Português.

    Infelizmente por falta de colaboradores para fazer as traduções, o thunderbird 31 foi lançado parcialmente traduzido para o nosso idioma, mas esse problema será resolvido no thunderbird 38.

  • A página Firefox - histórico, entre outros está em outro idioma... como posso alterar?

    A página está em inglês e gostaria de alterar para o português

    Ola Naah1990,
    Na janela de opções do FFx, clique na aba "Conteúdo" em seguida, na sessão Idiomas, clique em "Selecionar" e depois escolha o idioma que desejar e clique em "Adicionar".
    Opcionalmente, vc pode remover outros idiomas que não te interessem.
    Depois disso reinicie o FFx e teste o programa.
    Se o problema persistir, tente desinstalar o FFx e baixe uma versao do instalador no idioma desejado nesta pagina: http://www.mozilla.org/en-US/firefox/all/
    No caso, para Português do Brasil, o link é este:
    https://download.mozilla.org/?product=firefox-30.0&os=win&lang=pt-BR
    Boa sorte.

  • MM-SRV - Múltiplos idiomas em textos curtos de serviços

    Boa tarde.
    Prezados,
    Ativei o mestre de serviços aqui no cliente e em seguida criei as hierarquia, usando a funcionalidade da transação ML10. Nessa transação criei uma hierarquia com nível I, nível II e nível III, e acabei esbarrando numa particularidade da nota SAP 635456.
    As hierarquias criadas pela transação ML10 não permite usar dois idiomas, no caso aqui do cliente seria PT e ES. Se a hierarquia é criada no idioma PT,  ela continua exibindo as informações em português, mesmo quando o usuário se loga em espanhol.
    Alguém conhece um meio de fazer com que o usuário possa visualizar as informações de acordo com o idioma do login, PT e ES?
    Desde já, agradeço a todos pela atenção.
    Atenciosamente,
    Jefferson Rainha

    Otho,
    A estrutura de dados do extrator  2LIS_02_SRV  é novo desde o EHP3 e há alguns
    passos para ativá-lo. Como você disse, a BF  LOG_MM_C1_2 deve ser ativado na Tcode
    SFW5,  a ativação deve ser realizada completamente.
    Abs
    Alexandre

  • Photoshop Elements 6.0 - Idioma

    Hola a todos:
                          Algunos años atrás he comprado un ordenador y traía ya instalado (sin disco) Adobe Photoshop Elements 6.0 en inglés. Mi consulta es saber si puedo incorporar el idioma español sin tener el disco de instalación (si existe algún tipo de patch o nueva descarga). Desde ya, muchas gracias a todos por vuestra atención.

    I don't think you can, but maybe someone else will know. You would need the original installation media, I think.

  • Cambio de idioma predeterminado en la instalacion del acrobat 9.0 professional

    LA INSTALACION ES DESATENDIDA Y HEMOS UTILIZADO EL ADOBE CUSTOMIZATION WIZARD 9.0
    NECESITAMOS CAMBIAR EL IDIOMA DEL INSTALADOR DE ACROBAT 9.0 PRO.
    EL INSTALADOR DE ACROBAT ES EN ITALIANO ESPAÑOL HOLANDES Y PORTUGUES
    POR DEFECTO LA INSTALACION NOS LA HACE EN ITALIANO Y NECESITAMOS QUE LA INSTALACION POR DEFECTO SEA EN ESPAÑOL.
    DESPUES DE HABLAR CON VOSOTROS NOS COMENTASTEIS QUE UTILIZARAMOS EL ACROBATUPD913_ALL_INCR.MSP PARA CAMBIAR EL IDIOMA POR DEFECTO.
    PERO NOS DA EL SIGUIENTE ERROR
    EL SERVICIO DE WINDOWS INSTALLER NO PUEDE INSTALAR LA REVISION DE ACTUALIZACION PORQUE NO SE ENCUENTRA EL PROGRAMA QUE SE ACTUALIZARA, O BIEN PORQUE LA REVISION DE ACTUALIZACION ES PARA OTRA VERSION DEL PROGRAMA. COMPRUEBE QUE EL PROGRAMA QUE DESEA ACTUALIZAR ESTA INSTALADO EN EL EQUIPO Y SI DISPONE DE LA ACTULIZACION CORRECTA.
    HEMOS COMPROBADO QUE NO HAY UN ACROBATUPD PARA ESTA VERSION.
    NECESITAMOS SOLVENTAR EL PROBLEMA YA QUE ESTAMOS ATASCADOS.
    UN CORDIAL SALUDO:

    Consulta por favor este documento:
    http://helpx.adobe.com/x-productkb/policy-pricing/creative-suite-2-activation-end-life.htm l
    Confirma por favor que resuelve tu problema y marca como contestada tu pregunta para facilitar su consulta a otros usuarios. gracias.

  • Memory sensitive cache? (Clearing Softreference only when necessary)

    I have a number of objects that I load into memory from files. These are large objects, and I cannot have all of them in memory at the same time. However, because they take time to load, I would like to load them in as seldom as possible. SoftReferences seemed to be an ideal way to do this, except that the objects pointed to by my SoftReferences are being finalized long before I run out of available memory.
    Is there a way to have these references hang around as long as possible? Ideally, they'd only clear if an OutOfMemory error is about to be thrown.
    Mark McKay

    Well, I am having the exact same issue -- and only one month after you are. I have objects, loaded slowly from xml files, which i cache in memory. Typically there will only be dozens or hundreds of them, but sometimes there will be thousands or tens of thousands, and I would like to improve my cache (which is currently just a Hashtable and a wrapper) to be contextually memory-sensitive.
    I'm confused as to the difference between a SoftReference and a WeakReference, especially since it seems to me that a SoftReference is the way to go but, as I look around the web for advice, most people seem to prefer WeakReferences. Since I'm leaning toward SoftReferences, I guess I don't want to use a WeakHashMap, rather I want a SoftRefHashtable of some kind, which perhaps I will have to implement.
    If I roll my own, is it as simple as overriding get() and put() to wrap the parameters in SoftReferences, and unwrap them back into objects?

  • SoftReference and WeakReference clearing

    According to the javadoc of SoftReference:
    http://java.sun.com/javase/6/docs/api/java/lang/ref/SoftReference.html:
    Suppose that the garbage collector determines at a certain point in time that an object is softly reachable. At that time it may choose to clear atomically all soft references to that object and all soft references to any other softly-reachable objects from which that object is reachable through a chain of strong references.So all SoftReferences will be cleared atomically. Will WeakReferences be cleared at the same time atomically with the clearing of the SoftReferences?
    In other words, is it possible that WeakReference.get can return a hard reference after the soft reference has been cleared by the garbage collector?
    Cheers,
    Dave.

    Here is my test application which shows it works the way I was expecting, both references get cleared at the same time:
    a_garbage_b_not: 0
    b_garbage_a_not: 0
    both_garbage: 2000However, I'm not sure this is conclusive enough and would please like confirmation and/or a link to some garbage collection documentation that states this is how it works.
    public class Main {
        public static void main(String[] args) {
            int a_garbage_b_not = 0;
            int b_garbage_a_not = 0;
            int both_garbage = 0;
            int idx = 0;
            while (idx < 1000000)
                int jdx = 0;
                while (jdx++ < 100)
                    idx++;
                    ObjectA obj_a = new ObjectA(new ObjectB());
                    WeakReference weak_a = new WeakReference(obj_a);
                    WeakReference weak_b = new WeakReference(obj_a.obj_b);
                    obj_a = null;
                    boolean a_garbaged = false;
                    boolean b_garbaged = false;
                    int loop = 0;
                    ArrayList rubbish = new ArrayList();
                    while (!a_garbaged && !b_garbaged)
                        rubbish.add(new Object());
                        loop++;
                        a_garbaged = weak_a.get() == null;
                        b_garbaged = weak_b.get() == null;
                    rubbish = null;
                    if (a_garbaged && b_garbaged) {
                        System.out.println(idx + ": both_garbage, loops: " + loop);
                        both_garbage++;
                    else if (a_garbaged && !b_garbaged) {
                        System.out.println(idx + ": a_garbage_b_not, loops: " + loop);
                        a_garbage_b_not++;
                    else if (!a_garbaged && b_garbaged) {
                        System.out.println(idx + ": b_garbage_a_not, loops: " + loop);
                        b_garbage_a_not++;
                System.out.println("a_garbage_b_not: " + a_garbage_b_not);
                System.out.println("b_garbage_a_not: " + b_garbage_a_not);
                System.out.println("both_garbage:    " + both_garbage);
        private static class ObjectA
            private final ObjectB obj_b;
            private ObjectA(ObjectB obj_b)
                this.obj_b = obj_b;
        private static class ObjectB
    }Cheers,
    Dave.

  • Inicio con MAVERICKS 10.9.2 y se cambia el idioma del teclado a ingles estadounidense.

    Cuando inicio Macbooks con OS X MAVERICKS 10.9.2, que acabo de reinstalar, se cambia el idioma del teclado a ingles estadounidense. Lo cambio en preferencias de sistema, pero al volver a iniciar... otra vez igual. 
    Es decir, no puedo cambiar el idioma del teclado por defecto a Español ISO, ni ningún otro. Siempre se establece por defecto el Ingles estadounidense. He cambiado la fuente de entrada, pero nada... se vuelve a poner el ingles por defecto.
    He probado tambien a cambiar el idioma desde el Terminal, eligiendo el número de idioma, pero... al volver a iniciar... otra vez igual.
    ¿Alguien podria echar una manilla?. Gracias.

    Try booting into safe mode (hold SHIFT key down while booting).

  • Illustrator CS2-CS3, Cambiar idioma de los menus

    Algo que quisiera saber si se puede hacer es cambiar el idioma de los menus del illustrator, despues de que ya ha sido instalado digamos en ingles, cambiarlo a Espanol.

    Necesito que me resolvais un problemilla... no sé cómo volver a restablecer el marco de selección que me permite escalar "tirando" de una esquinita, la imagen o cuadro o lo que sea!
    Por favor que alguien me conteste que me he bloqueado [email protected]

  • Clarification of the handle/body idiom in multi threaded applications

    Hello
    As some DBXML classes use the handle-body idiom (handle/body idiom in some docs), could someone please clarify the consequences of that in a multi threaded application like a web container?
    For 100% Java people, like me, this is known in the Java world as 'programming towards interfaces', or as the Bridge pattern; which is seen as good practice.
    Let's take an example. The class XmlQueryContext is not thread safe, but it has a copy constructor. Imagine that your web application has one XmlQueryContext, that we never use in a query, but that we prepare only to be copied in new threads. Is it thus safe to instantiate various new XmlQueryContexts using that copy constructor in various new threads and use them simultaneously?
    Thank you
    Koen
    PS What I am really asking here is if somebody could please translate the following to Java parlé:
    A copy constructor is provided for this class. The class is implemented using a handle-body idiom. When a handle is copied both handles maintain a reference to the same body.

    As a Java user you do not have to worry about how the C++ copy constructors behave. In the Java API if a copy constructor exists for the object, then the copy constructor will copy all of the original object's data into a new object (XmlContainer is the one exception to this rule, generally one should not use that copy constructor at all). So in short, what you plan to do will work.
    Lauren Foutz

  • Can anyone explain the use of PhantomReference

    Can anyone explain the use of PhantomReference( if possible by an example..).

    Payment request is a noted document and as such does not pass any accounting entry. For effecting a payment to a
    Against the payment request you can effect the down payment. Suppose u have completly automated payment system and if you want to effect a down payment, you can do it only by payment request.
    Payment requests can be controlled through workflow for proper autorization.

  • Have bought service below to convert pdf files into word excel, Have followed instructions but cannot convert file. Please help.  AD003225761BR Produtos pedidos: Qtd. produto 1 Adobe ExportPDF, Annual (Outro,Todos os idiomas disponíveis) My email: toledo-

    Have bought service below to convert pdf files into word excel, Have followed instructions but cannot convert file. Please help.
    AD003225761BR Produtos pedidos: Qtd. produto 1 Adobe ExportPDF, Annual (Outro,Todos os idiomas disponíveis) My email: [email protected]

    Hi Jwalter,
    Thank you for posting on the Adobe forums,Please let us know what is the exact issue.
    Also, if you want help on how to use the service, kindly try the link below.
    Adobe ExportPDF FAQ
    http://tv.adobe.com/watch/insights-on-acrobat-solutions/introduction-to-adobe-exportpdf/
    Thanks,
    Vikrantt Singh

  • SoftReference is too soft

    My understanding of the SoftReference (package java.lang.ref) was that the garbage collector collects SoftReferenced object "only when it determines that where is not enough memory( and objects don't have hard references, of course)). However, this does not seems to be true.
    I have tried to use SoftReference for managing cache (cached objects were cloned and did not have any hard references). Although I had 10MB of free memory, garbage collector quickly collected all the objects?!
    I have used jdk 1.3 on WindowsNT.
    My intention was to prevent unlimited growth of the cache, but it seems to require more complex solution.
    Two question, is this behavior of SoftReferences a bug or a feature?
    Does anybody has an example/ reference of cache Management system?
    Thank you.
    Leo

    I didn't see your quote "only when it determines that there is not enough memory" anywhere in the API documentation for SoftReference, but perhaps you quoted from somewhere else. The documentation says, in effect, that the garbage collector can discard SoftReferences any time that it, in its discretion, decides it needs to, and not just to avoid running out of memory. I'm using SoftReferences to keep a large collection of similar objects in a HashMap, and in my experience if one of those objects doesn't have any references, it disappears pretty quickly. My cache has a "get" method that retrieves the object from the database if it has been garbage collected; this rarely happens, because the objects are normally all linked together in a tree structure, but it does happen when something else needs one of the objects that isn't already in the tree.
    So yes, you will need a more complex solution.

  • Como cambiar el idioma de Adobe Audition CS5.5

    Hola a todos. Recientemente conseguí la versión de Adobe Audition CS5.5 y al ejecutarlo me aparece todo en alemán. Y me preguntaba si alguien me pordría enseñar a cambiar de alemána a inglés. Gracias.
    Hi there. Recently I get the new version of Adobe Audition CS5.5 and when a run it, it is in german. And I was wondering if someone could teach me how to change de leguaje to English instead of german. Thank you.

    Hola Cool Dising
    me puse a desmenuzar el programa y no encontre ningun boton o pestaña con la funcion directa para cambiar el idioma
    directamente
    trate de buscar por medio de las carpetas de archivos de programa
    Y metiendome a la carpeta de AMT ahi estas todas las carpetas con las diferentes opciones de idioma
    trate de activar o cambiar  desde ahi y te soy sincero "no pude"
    creo que la opcion mas sana para no afectar tu programa con alguna futura falla
    es desinstalar el programa  y re-instalalo para que desde el inicio  elijas el Idioma con el que te sientas mas comodo
    al trabajar en adobe Audition
    Suerte y excelente Grabaciones
    saludos.
    Enrique Arista/Creativox Pro Studio

Maybe you are looking for