fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12.  
  13. Set < UUID > set =
  14. Collections.synchronizedSet(
  15. Collections.newSetFromMap(
  16. new WeakHashMap <>()
  17. )
  18. );
  19.  
  20. UUID uuid1 = UUID.fromString( "a8ee1e34-cead-11e8-a8d5-f2801f1b9fd1" );
  21. UUID uuid2 = UUID.fromString( "39bda2b4-5885-4f56-a900-411a49beebac" );
  22. UUID uuid3 = UUID.fromString( "0b630385-0452-4b96-9238-20cdce37cf55" );
  23. UUID uuid4 = UUID.fromString( "98d2bacf-3f7f-4ea0-9c17-c91f6702322c" );
  24.  
  25. System.out.println( "Size before adding: " + set.size() );
  26.  
  27. set.add( uuid1 );
  28. set.add( uuid2 );
  29. set.add( uuid3 );
  30. set.add( uuid4 );
  31.  
  32. System.out.println( "Size after adding 4 items: " + set.size() ); // Expect 4.
  33.  
  34. set.remove( uuid3 );
  35.  
  36. System.out.println( "Size after removing item # 3: " + set.size() ); // Expect 3.
  37.  
  38. uuid2 = null; // Release that UUID to garbage-collection.
  39. System.gc(); // Ask the JVM to run the garbage-collection. Only a suggestion, may be ignored.
  40. try {
  41. Thread.sleep( 1_000 ); // Wait a moment, just for the heck of it.
  42. } catch ( InterruptedException e ) {
  43. e.printStackTrace();
  44. }
  45.  
  46. System.out.println( "Size after making garbage of item # 2: " + set.size() ); // Expect 2.
  47.  
  48. }
  49. }
Success #stdin #stdout 0.08s 2184192KB
stdin
Standard input is empty
stdout
Size before adding: 0
Size after adding 4 items: 4
Size after removing item # 3: 3
Size after making garbage of item # 2: 2