Java7 WeakHashMap isEmpty() seems wrongWhat is a WeakHashMap and when to use it?Can I have someone verify my collections for the SCJP ExamClone a Singleton objectWorking on a java based chatting application using threadingHow can i copy error from console to file and where to include the code and what will be the code?Java - Method executed prior to Default ConstructorCollection stacks isEmpty methodWhen use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regexChangeListener ObservableMap “oldValue” is copy of newValueWould it make any difference giving arguments using scanner class instead of command line arguments?

French license plates

Difference between two vector layer

How do my husband and I get over our fear of having another difficult baby?

A famous scholar sent me an unpublished draft of hers. Then she died. I think her work should be published. What should I do?

What does it mean by "my days-of-the-week underwear only go to Thursday" in this context?

How to study endgames?

Can I pay some of the cost of an activated ability lots of times to get more out of the effect?

How important is knowledge of trig identities for use in Calculus

How many space launch vehicles are under development worldwide?

Why does `FindFit` fail so badly in this simple case?

Can a passenger predict that an airline is about to go bankrupt?

Lost passport and visa, tried to reapply, got rejected twice. What are my next steps?

Why are the wings of some modern gliders tadpole shaped?

Is there an in-universe explanation of how Frodo's arrival in Valinor was recorded in the Red Book?

Why would an airline put 15 passengers at once on standby?

Would an object shot from earth fall into the sun?

Is determiner 'a' needed in "one would call such a value a constant"?

Speed and Velocity in Russian

802.1Q Tagged BPDU?

What organs or modifications would be needed to have hairy fish?

Windows 10 deletes lots of tiny files super slowly. Anything that can be done to speed it up?

How to stop the death waves in my city?

Creating specific options in `Manipulate[]`

Is there a faster way or keyboard shortcut to close files without saving in Preview?



Java7 WeakHashMap isEmpty() seems wrong


What is a WeakHashMap and when to use it?Can I have someone verify my collections for the SCJP ExamClone a Singleton objectWorking on a java based chatting application using threadingHow can i copy error from console to file and where to include the code and what will be the code?Java - Method executed prior to Default ConstructorCollection stacks isEmpty methodWhen use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regexChangeListener ObservableMap “oldValue” is copy of newValueWould it make any difference giving arguments using scanner class instead of command line arguments?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















I'm trying to use Java7's WeakHashMap and I found its isEmpty() method give me wrong results.



import java.util.Map;
import java.util.WeakHashMap;

public class Test


public static void main(final String[] args)

final Map<String, Boolean> map = new WeakHashMap<>();

String b = new String("B");
map.put(b, true);
b = null;

System.gc();
System.out.println(map.isEmpty());
System.out.println(map.keySet().isEmpty());
System.out.println(map);





The actual result:



false



true





That is to say,



map.isEmpty() and map.keySet().isEmpty() is not consistent.
Can someone help me to understand it? Thanks a lot.










share|improve this question



















  • 2





    From Java 8 API doc for the class: "Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries." and "..it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true..", so I see no reason for worry.

    – yegodm
    Mar 28 at 19:58






  • 1





    Check this

    – Leonardo Alves Machado
    Mar 28 at 19:59

















4















I'm trying to use Java7's WeakHashMap and I found its isEmpty() method give me wrong results.



import java.util.Map;
import java.util.WeakHashMap;

public class Test


public static void main(final String[] args)

final Map<String, Boolean> map = new WeakHashMap<>();

String b = new String("B");
map.put(b, true);
b = null;

System.gc();
System.out.println(map.isEmpty());
System.out.println(map.keySet().isEmpty());
System.out.println(map);





The actual result:



false



true





That is to say,



map.isEmpty() and map.keySet().isEmpty() is not consistent.
Can someone help me to understand it? Thanks a lot.










share|improve this question



















  • 2





    From Java 8 API doc for the class: "Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries." and "..it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true..", so I see no reason for worry.

    – yegodm
    Mar 28 at 19:58






  • 1





    Check this

    – Leonardo Alves Machado
    Mar 28 at 19:59













4












4








4


1






I'm trying to use Java7's WeakHashMap and I found its isEmpty() method give me wrong results.



import java.util.Map;
import java.util.WeakHashMap;

public class Test


public static void main(final String[] args)

final Map<String, Boolean> map = new WeakHashMap<>();

String b = new String("B");
map.put(b, true);
b = null;

System.gc();
System.out.println(map.isEmpty());
System.out.println(map.keySet().isEmpty());
System.out.println(map);





The actual result:



false



true





That is to say,



map.isEmpty() and map.keySet().isEmpty() is not consistent.
Can someone help me to understand it? Thanks a lot.










share|improve this question














I'm trying to use Java7's WeakHashMap and I found its isEmpty() method give me wrong results.



import java.util.Map;
import java.util.WeakHashMap;

public class Test


public static void main(final String[] args)

final Map<String, Boolean> map = new WeakHashMap<>();

String b = new String("B");
map.put(b, true);
b = null;

System.gc();
System.out.println(map.isEmpty());
System.out.println(map.keySet().isEmpty());
System.out.println(map);





The actual result:



false



true





That is to say,



map.isEmpty() and map.keySet().isEmpty() is not consistent.
Can someone help me to understand it? Thanks a lot.







java weakhashmap






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 19:53









PengPeng

254 bronze badges




254 bronze badges










  • 2





    From Java 8 API doc for the class: "Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries." and "..it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true..", so I see no reason for worry.

    – yegodm
    Mar 28 at 19:58






  • 1





    Check this

    – Leonardo Alves Machado
    Mar 28 at 19:59












  • 2





    From Java 8 API doc for the class: "Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries." and "..it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true..", so I see no reason for worry.

    – yegodm
    Mar 28 at 19:58






  • 1





    Check this

    – Leonardo Alves Machado
    Mar 28 at 19:59







2




2





From Java 8 API doc for the class: "Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries." and "..it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true..", so I see no reason for worry.

– yegodm
Mar 28 at 19:58





From Java 8 API doc for the class: "Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries." and "..it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true..", so I see no reason for worry.

– yegodm
Mar 28 at 19:58




1




1





Check this

– Leonardo Alves Machado
Mar 28 at 19:59





Check this

– Leonardo Alves Machado
Mar 28 at 19:59












2 Answers
2






active

oldest

votes


















2
















WeakHashMap::isEmpty says:




...This result is a snapshot, and may not reflect unprocessed entries
that will be removed before next attempted access because they are no
longer referenced.




So you would expect that isEmpty() returns the correct value after GC and after access. This code demonstrates this:



public class Scratch1 
public static void main(final String[] args)
final Map<String, Boolean> map = new WeakHashMap<>();

String b = new String("B");
map.put(b, true);
b = null;

System.gc();

// map not internally accessed at this point
System.out.println(map.isEmpty());

// let's access the Map's internals (and hopefully coerce
// it into removing no-longer-referenced keys)
System.out.println(map.keySet()
.isEmpty());

// map HAS now been accessed
System.out.println(map.isEmpty());





Yields:



false
true
true





share|improve this answer


































    7
















    You should read the javadoc of WeakHashMap:




    The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.




    The short of all that is the the effects you've seen are entirely valid.






    share|improve this answer

























    • Just curious, what's the point of using WeakHashMap then?

      – Eric Duminil
      Mar 28 at 20:04






    • 1





      @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

      – Andreas
      Mar 28 at 20:07













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405864%2fjava7-weakhashmap-isempty-seems-wrong%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2
















    WeakHashMap::isEmpty says:




    ...This result is a snapshot, and may not reflect unprocessed entries
    that will be removed before next attempted access because they are no
    longer referenced.




    So you would expect that isEmpty() returns the correct value after GC and after access. This code demonstrates this:



    public class Scratch1 
    public static void main(final String[] args)
    final Map<String, Boolean> map = new WeakHashMap<>();

    String b = new String("B");
    map.put(b, true);
    b = null;

    System.gc();

    // map not internally accessed at this point
    System.out.println(map.isEmpty());

    // let's access the Map's internals (and hopefully coerce
    // it into removing no-longer-referenced keys)
    System.out.println(map.keySet()
    .isEmpty());

    // map HAS now been accessed
    System.out.println(map.isEmpty());





    Yields:



    false
    true
    true





    share|improve this answer































      2
















      WeakHashMap::isEmpty says:




      ...This result is a snapshot, and may not reflect unprocessed entries
      that will be removed before next attempted access because they are no
      longer referenced.




      So you would expect that isEmpty() returns the correct value after GC and after access. This code demonstrates this:



      public class Scratch1 
      public static void main(final String[] args)
      final Map<String, Boolean> map = new WeakHashMap<>();

      String b = new String("B");
      map.put(b, true);
      b = null;

      System.gc();

      // map not internally accessed at this point
      System.out.println(map.isEmpty());

      // let's access the Map's internals (and hopefully coerce
      // it into removing no-longer-referenced keys)
      System.out.println(map.keySet()
      .isEmpty());

      // map HAS now been accessed
      System.out.println(map.isEmpty());





      Yields:



      false
      true
      true





      share|improve this answer





























        2














        2










        2









        WeakHashMap::isEmpty says:




        ...This result is a snapshot, and may not reflect unprocessed entries
        that will be removed before next attempted access because they are no
        longer referenced.




        So you would expect that isEmpty() returns the correct value after GC and after access. This code demonstrates this:



        public class Scratch1 
        public static void main(final String[] args)
        final Map<String, Boolean> map = new WeakHashMap<>();

        String b = new String("B");
        map.put(b, true);
        b = null;

        System.gc();

        // map not internally accessed at this point
        System.out.println(map.isEmpty());

        // let's access the Map's internals (and hopefully coerce
        // it into removing no-longer-referenced keys)
        System.out.println(map.keySet()
        .isEmpty());

        // map HAS now been accessed
        System.out.println(map.isEmpty());





        Yields:



        false
        true
        true





        share|improve this answer















        WeakHashMap::isEmpty says:




        ...This result is a snapshot, and may not reflect unprocessed entries
        that will be removed before next attempted access because they are no
        longer referenced.




        So you would expect that isEmpty() returns the correct value after GC and after access. This code demonstrates this:



        public class Scratch1 
        public static void main(final String[] args)
        final Map<String, Boolean> map = new WeakHashMap<>();

        String b = new String("B");
        map.put(b, true);
        b = null;

        System.gc();

        // map not internally accessed at this point
        System.out.println(map.isEmpty());

        // let's access the Map's internals (and hopefully coerce
        // it into removing no-longer-referenced keys)
        System.out.println(map.keySet()
        .isEmpty());

        // map HAS now been accessed
        System.out.println(map.isEmpty());





        Yields:



        false
        true
        true






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 28 at 20:09

























        answered Mar 28 at 20:04









        Not a JDNot a JD

        1,3972 silver badges12 bronze badges




        1,3972 silver badges12 bronze badges


























            7
















            You should read the javadoc of WeakHashMap:




            The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.




            The short of all that is the the effects you've seen are entirely valid.






            share|improve this answer

























            • Just curious, what's the point of using WeakHashMap then?

              – Eric Duminil
              Mar 28 at 20:04






            • 1





              @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

              – Andreas
              Mar 28 at 20:07















            7
















            You should read the javadoc of WeakHashMap:




            The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.




            The short of all that is the the effects you've seen are entirely valid.






            share|improve this answer

























            • Just curious, what's the point of using WeakHashMap then?

              – Eric Duminil
              Mar 28 at 20:04






            • 1





              @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

              – Andreas
              Mar 28 at 20:07













            7














            7










            7









            You should read the javadoc of WeakHashMap:




            The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.




            The short of all that is the the effects you've seen are entirely valid.






            share|improve this answer













            You should read the javadoc of WeakHashMap:




            The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.




            The short of all that is the the effects you've seen are entirely valid.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 28 at 19:59









            AndreasAndreas

            90.2k4 gold badges74 silver badges140 bronze badges




            90.2k4 gold badges74 silver badges140 bronze badges















            • Just curious, what's the point of using WeakHashMap then?

              – Eric Duminil
              Mar 28 at 20:04






            • 1





              @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

              – Andreas
              Mar 28 at 20:07

















            • Just curious, what's the point of using WeakHashMap then?

              – Eric Duminil
              Mar 28 at 20:04






            • 1





              @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

              – Andreas
              Mar 28 at 20:07
















            Just curious, what's the point of using WeakHashMap then?

            – Eric Duminil
            Mar 28 at 20:04





            Just curious, what's the point of using WeakHashMap then?

            – Eric Duminil
            Mar 28 at 20:04




            1




            1





            @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

            – Andreas
            Mar 28 at 20:07





            @EricDuminil As commented by Leonardo Alves Machado: Check What is a WeakHashMap and when to use it?

            – Andreas
            Mar 28 at 20:07


















            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405864%2fjava7-weakhashmap-isempty-seems-wrong%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해