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;
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
add a comment
|
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
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
add a comment
|
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
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
java weakhashmap
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
add a comment
|
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
add a comment
|
2 Answers
2
active
oldest
votes
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
add a comment
|
You should read the javadoc of WeakHashMap:
The behavior of the
WeakHashMapclass depends in part upon the actions of the garbage collector, so several familiar (though not required)Mapinvariants do not hold for this class. Because the garbage collector may discard keys at any time, aWeakHashMapmay behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on aWeakHashMapinstance and invoke none of its mutator methods, it is possible for thesizemethod to return smaller values over time, for theisEmptymethod to returnfalseand thentrue, for thecontainsKeymethod to returntrueand laterfalsefor a given key, for thegetmethod to return a value for a given key but later returnnull, for theputmethod to returnnulland theremovemethod to returnfalsefor 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.
Just curious, what's the point of usingWeakHashMapthen?
– 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
add a comment
|
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
add a comment
|
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
add a comment
|
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
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
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
add a comment
|
add a comment
|
You should read the javadoc of WeakHashMap:
The behavior of the
WeakHashMapclass depends in part upon the actions of the garbage collector, so several familiar (though not required)Mapinvariants do not hold for this class. Because the garbage collector may discard keys at any time, aWeakHashMapmay behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on aWeakHashMapinstance and invoke none of its mutator methods, it is possible for thesizemethod to return smaller values over time, for theisEmptymethod to returnfalseand thentrue, for thecontainsKeymethod to returntrueand laterfalsefor a given key, for thegetmethod to return a value for a given key but later returnnull, for theputmethod to returnnulland theremovemethod to returnfalsefor 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.
Just curious, what's the point of usingWeakHashMapthen?
– 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
add a comment
|
You should read the javadoc of WeakHashMap:
The behavior of the
WeakHashMapclass depends in part upon the actions of the garbage collector, so several familiar (though not required)Mapinvariants do not hold for this class. Because the garbage collector may discard keys at any time, aWeakHashMapmay behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on aWeakHashMapinstance and invoke none of its mutator methods, it is possible for thesizemethod to return smaller values over time, for theisEmptymethod to returnfalseand thentrue, for thecontainsKeymethod to returntrueand laterfalsefor a given key, for thegetmethod to return a value for a given key but later returnnull, for theputmethod to returnnulland theremovemethod to returnfalsefor 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.
Just curious, what's the point of usingWeakHashMapthen?
– 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
add a comment
|
You should read the javadoc of WeakHashMap:
The behavior of the
WeakHashMapclass depends in part upon the actions of the garbage collector, so several familiar (though not required)Mapinvariants do not hold for this class. Because the garbage collector may discard keys at any time, aWeakHashMapmay behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on aWeakHashMapinstance and invoke none of its mutator methods, it is possible for thesizemethod to return smaller values over time, for theisEmptymethod to returnfalseand thentrue, for thecontainsKeymethod to returntrueand laterfalsefor a given key, for thegetmethod to return a value for a given key but later returnnull, for theputmethod to returnnulland theremovemethod to returnfalsefor 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.
You should read the javadoc of WeakHashMap:
The behavior of the
WeakHashMapclass depends in part upon the actions of the garbage collector, so several familiar (though not required)Mapinvariants do not hold for this class. Because the garbage collector may discard keys at any time, aWeakHashMapmay behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on aWeakHashMapinstance and invoke none of its mutator methods, it is possible for thesizemethod to return smaller values over time, for theisEmptymethod to returnfalseand thentrue, for thecontainsKeymethod to returntrueand laterfalsefor a given key, for thegetmethod to return a value for a given key but later returnnull, for theputmethod to returnnulland theremovemethod to returnfalsefor 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.
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 usingWeakHashMapthen?
– 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
add a comment
|
Just curious, what's the point of usingWeakHashMapthen?
– 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
add a comment
|
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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