Java.util.Set

This is related to the iterator;
Here is a snipet of the code,
               while(alive){
                    x = input.readInt();
                    y = input.readInt();
                    size = input.readInt();
                    int h = 0;
                    if(size == -1){}
                    else{
                    while(true){
                         x1 = (int) input.readInt();
                         if(x1 == -1){
                              break;
                         y1 = (int) input.readInt();
                         bullets.add(new Integer(x1));
                         bullets.add(new Integer(y1));
                         System.out.println("Recieved Bullet At - " + x1 + ", " + y1);
                         h++;
                    main.updateAll(x, y, playerNumber, bullets );
                    System.out.println("Bullets Size On Server = " + bullets.size());
                    bullets.clear();
                    x = 0;
                    y = 0;
And then the main.updateAll() method:
Iterator i = players.iterator();
                    while(i.hasNext()){
                    io = (ServerIO) i.next();
                    if(io.playerNumber == playerNum){}
                    else{
                         io.output.writeInt(x);
                         io.output.writeInt(y);     
                         io.output.flush();
                         io.output.writeInt(1);
                         System.out.println(bullets.size() + " Sent Bullet Size");
                         io.output.flush();
                         Iterator itt = bullets.iterator();
                         while(itt.hasNext()){
                              int bx = (Integer)itt.next();
                              int by = (Integer)itt.next();
                              io.output.writeInt(bx);
                              io.output.writeInt(by);
                              io.output.flush();
                              System.out.println("Sent Bullet X Y" + bx + ", " + by);
                         io.output.writeInt(-1);
                         io.output.flush();
                    }Ok it produces this output:
Recieved Bullet At - 742, 381
2 Sent Bullet Size
Sent Bullet X Y742, 381
Bullets Size On Server = 2
0 Sent Bullet Size
Bullets Size On Server = 0
Recieved Bullet At - 741, 381
2 Sent Bullet Size
Sent Bullet X Y381, 741
As u can see 1st tym the bullets are read out of the Set the way they were put in, the second tym however they wernt? the were read from the set the oposite way? Any ideas??

Set makes no guarantees about iteration order.
If you want them to come out in the same order in which they were put in, use LinkedHashSet.

Similar Messages

  • Getting compilation error: java.util.Set is an interface. This interface is not supported.

    Hi Folks,
    Is there a limitation in BEA's web services implementation? I have a simple web
    service that returns an array of java objects. However I am calling another middle
    tier API that returns a Set. I convert this Set into array of object and return
    it via the web service.
    However the .jws file that implements the webservice does not compile. I get the
    following error message:
    java.util.Set is an interface. This interface is not supported.
    Is there a limitation on using Collections within the .jws file? If that is the
    case it is a severe limitation.
    Note my Web Service API returns an array of java objects with no collections in
    them.
    Sanjay

    Hello,
    Generic java collections can only be handled in a very generic, weakly
    typed manner.
    Take a look at the
    http://workshop.bea.com/xmlbeans/guide/conXMLBeansSupportBuiltInSchemaTypes.html
    and also
    http://workshop.bea.com/xmlbeans/guide/conJavaTypesGeneratedFromUserDerived.html
    You might also ask your question to the XMLBeans newsgroup:
    http://newsgroups.bea.com/cgi-bin/dnewsweb?cmd=xover&group=weblogic.developer.interest.xmlbeans
    Regards,
    Bruce
    Sanjay wrote:
    >
    Hi Folks,
    Is there a limitation in BEA's web services implementation? I have a simple web
    service that returns an array of java objects. However I am calling another middle
    tier API that returns a Set. I convert this Set into array of object and return
    it via the web service.
    However the .jws file that implements the webservice does not compile. I get the
    following error message:
    java.util.Set is an interface. This interface is not supported.
    Is there a limitation on using Collections within the .jws file? If that is the
    case it is a severe limitation.
    Note my Web Service API returns an array of java objects with no collections in
    them.
    Sanjay

  • Puzzled by the redefinition of the methods in java.util.Set

    Hi all,
    I don't understand why those methods in java.util.Set redefined since their counterparts have alrealdy been defined in java.util.Collection and java.util.Set extends java.util.Collection. I agree to redefine boolean add(Object o) because its contract has been modified, but what about the rest like
    size() and iterator() ?
    Thanks.

    Hi all,
    I don't understand why those methods in
    in java.util.Set redefined since their counterparts
    have alrealdy been defined in java.util.Collection
    and java.util.Set extends java.util.Collection. I
    agree to redefine boolean add(Object o) because its
    contract has been modified, but what about the rest
    like
    size() and iterator() ?Completeness's sake?
    ~Cheers

  • Failed to unmarshal interface java.util.Set

    I am trying to get all mbeans using getAllMBeans() method after
    getting MBeanHome successfully. The method fails with the following
    error.
    Any clues ?
    Thanks
    karthik
    >>>>
    weblogic.rmi.extensions.RemoteRuntimeException: Unexpected Exception -
    with nested exception:
    [java.rmi.UnmarshalException: failed to unmarshal interface
    java.util.Set; nested exception is:
         java.io.InvalidClassException: javax.management.MBeanAttributeInfo;
    local class incompatible: stream classdesc serialVersionUID =
    7043855487133450673, local class serialVersionUID =
    8644704819898565848]
         at weblogic.management.internal.AdminMBeanHomeImpl_WLStub.getAllMBeans(Unknown
    Source)

    I am trying to get all mbeans using getAllMBeans() method after
    getting MBeanHome successfully. The method fails with the following
    error.
    Any clues ?
    Thanks
    karthik
    >>>>
    weblogic.rmi.extensions.RemoteRuntimeException: Unexpected Exception -
    with nested exception:
    [java.rmi.UnmarshalException: failed to unmarshal interface
    java.util.Set; nested exception is:
         java.io.InvalidClassException: javax.management.MBeanAttributeInfo;
    local class incompatible: stream classdesc serialVersionUID =
    7043855487133450673, local class serialVersionUID =
    8644704819898565848]
         at weblogic.management.internal.AdminMBeanHomeImpl_WLStub.getAllMBeans(Unknown
    Source)

  • TestNG with java.util.Set

    hi, i want to test simple method:
    @Parameters({"lista"})
    @Test
    public GroupedFiles groupFiles(Set<File> p_files){
    }and i have definition of my xml:
    <suite name="My suite">
      <parameter name="first-name"  value="Cedric"/>
      <test name="Simple example">
      <-- ... -->and my testNG throws me uknown for me exception:
    java.lang.AssertionError: Unsupported type parameter : interface java.util.Set
    could anyone help me with this case, thanks for any knowledge

    'little code modification'
    hi, i want to test simple method:
    @Parameters({"lista"})
    @Test
    public GroupedFiles groupFiles(Set<File> p_files){
    }and i have definition of my xml:
    <suite name="My suite">
      <parameter name="lista"  value="java.util.Set"/>
      <test name="Simple example">
      <-- ... -->and my testNG throws me uknown for me exception:
    java.lang.AssertionError: Unsupported type parameter : interface java.util.Set
    could anyone help me with this case, thanks for any knowledge

  • ADF Faces af:table support java.util.Set

    I was using a java.util.Set in my model classes, as implementation of the Collection interface. And wanted to show the Set using a <af:table> after a while I discoverded that the documentation did not mention support of java.util.Set, only List.
    Now I have to convert my collection to List in the backing beans of my view.
    Is there a better approch than converting every Set in the view using
    new Arraylist(set)?
    And what is the reason of the missing Set support (or General Colelction support)?
    Thank you

    Deepak, I don't think you know what you're writing about.
    No, we do not support java.util.Set in <af:table>. For that matter, neither does <h:dataTable>.
    The "why" of it is that we require indexed access into the table for operations like "Display rows 526-550". java.util.Set does not offer indexed access.
    By the way, one corollary - do not use java.util.LinkedList with tables (ADF Faces or the JSF data table). If the list is small, then it won't be a problem, but with a large list, you'll get brutal performance.

  • Java.util.set: problem with duplicate keys

    Hello, everybody,
    i have implemented a custom class C with its own equals()-method. I have two instances I1 and I2 of C with
    I1.equals(I2) = true
    if I add I1 and I2 to a set
    Set S = new HashSet();
    S.add(I1);
    S.add(I2);
    there are two elements I1 and I2 in the set. How is this possible?

    You must override the method hashCode() of your class C to be consistent with the comparison by equals() method.
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Object.html#hashCode()

  • How to Split java.util.Set object into multiple objects?

    Hi All,
    I'm having a collection of items in a Set. Assume that i'm having 10,000 items in Set A.
    Now i like to split the Set into multiple Set or Array such as each set or array consist of 100 records. i.e whenever
    i get more items i want to split them into mutiple set or array.
    Is there is any Java Api doesn't this function? or any other way to achieve this?
    Thanks,
    J.Kathir

    Iterate through them, placing them into different new collections.
    It may be easier to add the Set to a List, and then call sublist() a few times on the resulting List.

  • Why how Abstract class   for java.util.set

    I need to use Set i din't find any impelemnted class for Set, i don't want HashSet or LinkedHashSet just a Set is enough for my purpose.
    How can i take instance of AbstractSet it is abstract.....
    Is the only way is to write my own class extending AbstractSet.
    Or is there something which i'm missing
    TIA Nas

    Because Vector isn't an ancsetor of AbstractList.
    What you are trying to do is the same as saying that becasue my cousin and I have the same grandfather we must have the same parent which isn't true.
               Collection
            Set         List
       AbstractSet      AbstractList
       HashSet              Vector

  • Java.util.ConcurrentModification Exception

    Hi
    I am trying to write a caching object for my web application. I have a CacheMAnger thread which is started when Tomcat starts. I put objects onto the cache and give them a TTL. My thread occasionaly goes through and checks all the cached objects to see if they are expired. I thought this was a syncronization problem but I can't find where.
    It bombs when an object expires and gets removed form the cache. The error output is below as well as a copy of the CacheManager source.
    Thanks
    Michael
    <pre>
    2003-04-15 12:55:15,161 DEBUG cache.CacheManager$1 82 - CacheManager: CustomerList in Cache... expi
    ry?
    EXPIRY:Tue Apr 15 17:55:04 GMT 2003CURRENT:Tue Apr 15 17:55:15 GMT 2003
    2003-04-15 12:55:15,161 INFO cache.CacheManager$1 90 - CacheManager Removed CustomerList
    java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:750)
    at java.util.HashMap$KeyIterator.next(HashMap.java:786)
    at net.talisen.tsr.cache.CacheManager$1.run(CacheManager.java:77)
    at java.lang.Thread.run(Thread.java:536)
    </pre>
    =====================================================================
    <pre>
    package net.talisen.tsr.cache;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.Iterator;
    import org.apache.log4j.Logger;
    * Title: Caching
    * Description:
    * Copyright: Copyright (c) 2001
    * @author Michael Holly based on code from Jonathan Lurie in July 2001 Article in JavaWorld
    * @version 1.0
    public class CacheManager
    // This is the HashMap that contains all objects in the cache.
    private static java.util.HashMap cacheHashMap = new java.util.HashMap();
    // This object acts as a semaphore, which protects the HashMap
    // RESERVED FOR FUTURE USE private static Object lock = new Object();
    static
    try
    //Create background thread, which will be responsible for purging expired items.
    Thread threadCleanerUpper = new Thread( new Runnable()
    // The default time the thread should sleep between scans. The sleep
    // method takes in a millisecond value so 5000 = 5 Seconds.
    final static int milliSecondSleepTime = 20000;
    public void run()
    Logger log = Logger.getLogger(CacheManager.class);
    try
    // Sets up an infinite loop.
    while (true)
    log.debug( "CacheManager Scanning For Expired Objects...");
    // Get the set of all keys that are in cache. These are the unique
    // identifiers
    Set keySet = null;
    Iterator keys = null;
    Object key = null;
    Cacheable value = null;
    synchronized ( cacheHashMap )
    keySet = cacheHashMap.keySet();
    // An iterator is used to move through the Keyset //
    synchronized( keySet )
    keys = keySet.iterator();
    // Sets up a loop that will iterate through each key in the KeySet
    while(keys.hasNext())
    // Get the individual key. We need to hold on to this key
    // in case it needs to be removed
    synchronized ( keys )
    key = keys.next();
    // Get the cacheable object associated with the key inside the cache
    value = (Cacheable)cacheHashMap.get(key);
    log.debug( "CacheManager: " + value.getIdentifier() + " in Cache... expiry?");
    // Is the cacheable object expired?
    if (value.isExpired())
    //Yes it's expired! Remove it from the cache
    cacheHashMap.remove(key);
    cacheHashMap.notifyAll();
    log.info( "CacheManager Removed " + key.toString() );
    ***** A LRU (least-recently used) or
    LFU (least-frequently used) *****
    ******* would best be inserted here *****
    // Puts the thread to sleep. Don't need to check it continuously
    Thread.sleep( this.milliSecondSleepTime);
    catch (Exception e)
    e.printStackTrace();
    return;
    } // End run method
    }); // End class definition and close new thread definition
    // Sets the thread's priority to the minimum value.
    threadCleanerUpper.setPriority( Thread.MIN_PRIORITY );
    // Starts the thread.
    threadCleanerUpper.start();
    catch(Exception e)
    System.out.println( "CacheManager.Static Block: " + e);
    } // End static block
    // default constructor
    public CacheManager()
    * Used to add an object to the Cache
    * @param object the object to be added to the cache
    public static void putCache(Cacheable object)
    Logger log = Logger.getLogger(CacheManager.class);
    // Remember if the HashMap previously contains a mapping for the key, the old value
    // will be replaced. This is valid functioning.
    if ( object == null ) {
    log.debug("object to be cached is null. Caching was not attempted");
    return;
    if ( object.getIdentifier() == null ) {
    log.debug("object to be cached has a null key. Caching was not attempted");
    return;
    else
    synchronized ( cacheHashMap ) {
    cacheHashMap.put(object.getIdentifier(), object);
    log.debug( object.getIdentifier() + " cached");
    * Used to get an object from the cache
    * @param object the object to be retrieved from the cache
    * @return the cached object
    public static Cacheable getCache(Object identifier)
    Logger log = Logger.getLogger(CacheManager.class);
    if (identifier == null ) {
    log.debug( "Cache key was null" );
    return null;
    log.debug("Looking for " + identifier.toString() );
    //synchronized (lock) // UNCOMMENT LINE XXX
    //{                    // UNCOMMENT LINE XXX
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = ( Cacheable )cacheHashMap.get(identifier);
    // The code to create the object would be placed here.
    //} // UNCOMMENT LINE XXX
    if (object == null) {
    log.debug( "object not found in cache");
    return null;
    if (object.isExpired())
    log.debug( "object in cache was expired");
    synchronized ( cacheHashMap ) {
    cacheHashMap.remove(identifier);
    return null;
    else
    log.debug( object.getIdentifier() + " found");
    object.incrementCacheHits(); // track the performance
    return object;
    * Used to clear all objects from the cache
    public static void emptyCache()
    Logger log = Logger.getLogger(CacheManager.class);
    synchronized ( cacheHashMap ) {
    cacheHashMap.clear();
    log.debug( "Cache cleared");
    * Used to remove a particular object from the cache
    * @param identifier the object to be removed from the cache
    public static void removeEntry(Object identifier)
    Logger log = Logger.getLogger(CacheManager.class);
    if (identifier == null ) {
    log.debug( "Cache key was null" );
    return;
    synchronized ( cacheHashMap ) {
    cacheHashMap.remove(identifier);
    log.debug( identifier + " removed");
    * Used to get a count of cached objects
    * @return number of objects in the cache
    public static int getCount()
    synchronized ( cacheHashMap ) {
    return cacheHashMap.size();
    * Used to get a set of the entries in the cache
    * @param Set a set of the objects in the cache
    public static Set getEntrySet()
    synchronized ( cacheHashMap ) {
    return cacheHashMap.entrySet();
    * Used to get a html page on the status of the cache
    public static String getStatus()
    Set keySet = null;
    Iterator keys = null;
    synchronized (cacheHashMap) {
    keySet = cacheHashMap.keySet();
    keys = keySet.iterator();
    String status = new String();
    status += ( "<html><head>");
    status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
    status += ( "<meta http-equiv=\"refresh\" content=\"10\" /> ");
    status += ( "</head><body>" );
    status += ( "<p><h4>Cache Status " + (new java.util.Date()).toString() + "</h4>" );
    status += ( "<br>Page automagically refreshed every 10 seconds<br>" );
    status += ( getCount() + " object(s) cached" );
    status += ( "<p>Cache contains: " );
    while(keys.hasNext())
    Object key = keys.next();
    // Get the cacheable object associated with the key inside the cache
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = (Cacheable)cacheHashMap.get(key);
    status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>" );
    status += ( "<br>   <b>Class of:</b><i>" + object.toString() + "</i>");
    status += ( "<br>   <b> Expires at:</b><i>" + object.getExpireDate() + "</i>");
    status += ( "<br>   <b> Cache Hits:</b><i>" + object.getCacheHits().toString() + "</i>");
    status += ( "<br>   <b> Object Size:</b><i>" + object.getByteCount(object).toString() + "</i>");
    int bytesServed = object.getCacheHits().intValue() * object.getByteCount(object).intValue();
    double eff = 0.0;
    // handle divide by 0
    if ( bytesServed > 0 ) {
    eff = ( bytesServed - object.getByteCount(object).intValue() ) / bytesServed;
    status += ( "<br>   <b> Cache Efficiency:</b><i>" + eff + "</i><br><br>");
    status += ( "</body></html>" );
    return status;
    * Used to get a html page on the status of the cache
    public static String flushCache()
    Set keySet = null;
    Iterator keys = null;
    synchronized ( cacheHashMap ) {
    keySet = cacheHashMap.keySet();
    keys = keySet.iterator();
    String status = new String();
    status += ( "<html><head>");
    status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
    status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
    status += ( "</head><body>" );
    status += ( "<p><h4>Cache status before cache reset " + (new java.util.Date()).toString() + "</h4>" );
    status += ( "<p>Cache size: " + getCount() + " object(s) cached" );
    status += ( "<p>Cache contains: " );
    while(keys.hasNext())
    Object key = keys.next();
    // Get the cacheable object associated with the key inside the cache
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = (Cacheable)cacheHashMap.get(key);
    status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i> <b>Class of:</b><i>" + object.toString() );
    status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
    CacheManager.emptyCache();
    status += ( "<p><h4>Cache status after cache reset " + (new java.util.Date()).toString() + "</h4>" );
    status += ( "<p>Cache size: " + CacheManager.getCount() + " object(s) cached" );
    status += ( "<p>Cache contains: " );
    Set newKeySet = null;
    Iterator newKeys = null;
    synchronized ( cacheHashMap ) {
    newKeySet = cacheHashMap.keySet();
    newKeys = newKeySet.iterator();
    // this really never gets executed
    while(newKeys.hasNext())
    Object key = newKeys.next();
    // Get the cacheable object associated with the key inside the cache
    Cacheable object = null;
    synchronized ( cacheHashMap ) {
    object = (Cacheable)cacheHashMap.get(key);
    status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i> <b>Class of:</b><i>" + object.toString() );
    status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
    status += ( "</body></html>" );
    return status;
    </pre>

    I think my problem is that I am iterating through all the values of the hashMap and when I find one and delete it then the iterator becomes invalid? Checkout the while loop in the thread.
    I'm not sure that this scenario is consistant with the error I'm getting.
    I had tried something similar to what you described... maybe I missed something. Let me try it again...
    I have reposted my code below with the proper tags to render the code if you need to reference for any more suggestions.
    Michael
    package net.talisen.tsr.cache;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.Iterator;
    import org.apache.log4j.Logger;
    * Title:        Caching
    * Description:
    * Copyright:    Copyright (c) 2001
    * @author Michael Holly based on code from Jonathan Lurie in July 2001 Article in JavaWorld
    * @version 1.0
    public class CacheManager
       // This is the HashMap that contains all objects in the cache.
       private static java.util.HashMap cacheHashMap = new java.util.HashMap();
       // This object acts as a semaphore, which protects the HashMap
       // RESERVED FOR FUTURE USE  private static Object lock = new Object();
       static
          try
             //Create background thread, which will be responsible for purging expired items.
             Thread threadCleanerUpper = new Thread( new Runnable()
                //  The default time the thread should sleep between scans.  The sleep
                //  method takes in a millisecond value so 5000 = 5 Seconds.
                final static int milliSecondSleepTime = 20000;
                public void run()
                   Logger log = Logger.getLogger(CacheManager.class);
                   try
                      // Sets up an infinite loop.
                      while (true)
                         log.debug( "CacheManager Scanning For Expired Objects...");
                         // Get the set of all keys that are in cache.  These are the unique
                         // identifiers
                         Set keySet      = null;
                         Iterator keys   = null;
                         Object key      = null;
                         Cacheable value = null;
                         synchronized ( cacheHashMap )
                            keySet = cacheHashMap.keySet();
                            // An iterator is used to move through the Keyset //
                            synchronized( keySet )
                               keys = keySet.iterator();
                            // Sets up a loop that will iterate through each key in the KeySet
                            while(keys.hasNext())
                               // Get the individual key. We need to hold on to this key
                               // in case it needs to be removed
                               synchronized ( keys )
                                  key = keys.next();
                               // Get the cacheable object associated with the key inside the cache
                               value = (Cacheable)cacheHashMap.get(key);
                               log.debug( "CacheManager: " + value.getIdentifier() + " in Cache... expiry?");
                               // Is the cacheable object expired?
                               if (value.isExpired())
                                  //Yes it's expired! Remove it from the cache
                                  cacheHashMap.remove(key);
                                  cacheHashMap.notifyAll();
                                  log.info( "CacheManager Removed " + key.toString() );
                             ***** A LRU (least-recently used) or
                                                  LFU (least-frequently used) *****
                             ******* would best be inserted here              *****
                         // Puts the thread to sleep. Don't need to check it continuously
                         Thread.sleep( this.milliSecondSleepTime);
                   catch (Exception e)
                      e.printStackTrace();
                   return;
                } // End run method
             }); // End class definition and close new thread definition
             // Sets the thread's priority to the minimum value.
             threadCleanerUpper.setPriority( Thread.MIN_PRIORITY );
             // Starts the thread.
             threadCleanerUpper.start();
          catch(Exception e)
             System.out.println( "CacheManager.Static Block: " + e);
       } // End static block
       // default constructor
       public CacheManager()
       * Used to add an object to the Cache
       * @param object the object to be added to the cache
       public static void putCache(Cacheable object)
          Logger log = Logger.getLogger(CacheManager.class);
          // Remember if the HashMap previously contains a mapping for the key, the old value
          // will be replaced.  This is valid functioning.
          if ( object == null ) {
             log.debug("object to be cached is null. Caching was not attempted");
             return;
          if ( object.getIdentifier() == null ) {
             log.debug("object to be cached has a null key. Caching was not attempted");
             return;
          else
             synchronized ( cacheHashMap ) {
                cacheHashMap.put(object.getIdentifier(), object);
                log.debug( object.getIdentifier() + " cached");
       * Used to get an object from the cache
       * @param object the object to be retrieved from the cache
       * @return the cached object
       public static Cacheable getCache(Object identifier)
          Logger log = Logger.getLogger(CacheManager.class);
          if (identifier == null ) {
             log.debug( "Cache key was null" );
             return null;
          log.debug("Looking for " + identifier.toString() );
          Cacheable object = null;
          synchronized ( cacheHashMap )  {
             object = ( Cacheable )cacheHashMap.get(identifier);
          if (object == null) {
             log.debug( "object not found in cache");
             return null;
          if (object.isExpired())
             log.debug( "object in cache was expired");
             synchronized ( cacheHashMap )  {
                cacheHashMap.remove(identifier);
             return null;
          else
             log.debug( object.getIdentifier() + " found");
             object.incrementCacheHits(); // track the performance
             return object;
       * Used to clear all objects from the cache
       public static void emptyCache()
          Logger log = Logger.getLogger(CacheManager.class);
          synchronized ( cacheHashMap )  {
             cacheHashMap.clear();
          log.debug( "Cache cleared");
       * Used to remove a particular object from the cache
       * @param identifier the object to be removed from the cache
       public static void removeEntry(Object identifier)
          Logger log = Logger.getLogger(CacheManager.class);
          if (identifier == null ) {
             log.debug( "Cache key was null" );
             return;
          synchronized ( cacheHashMap )  {
             cacheHashMap.remove(identifier);
          log.debug( identifier + " removed");
       * Used to get a count of cached objects
       * @return number of objects in the cache
       public static int getCount()
          synchronized ( cacheHashMap )  {
             return cacheHashMap.size();
       * Used to get a set of the entries in the cache
       * @param Set a set of the objects in the cache
       public static Set getEntrySet()
          synchronized ( cacheHashMap )  {
             return cacheHashMap.entrySet();
       * Used to get a html page on the status of the cache
       public static String getStatus()
          Set keySet = null;
          Iterator keys = null;
          synchronized (cacheHashMap) {
             keySet = cacheHashMap.keySet();
             keys = keySet.iterator();
          String status = new String();
          status += ( "<html><head>");
          status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
          status += ( "<meta http-equiv=\"refresh\" content=\"10\" /> ");
          status += ( "</head><body>" );
          status += ( "<p><h4>Cache Status " + (new java.util.Date()).toString() + "</h4>" );
          status += ( "<br>Page automagically refreshed every 10 seconds<br>" );
          status += ( getCount() + " object(s) cached" );
          status += ( "<p>Cache contains: " );
          while(keys.hasNext())
             Object key = keys.next();
             // Get the cacheable object associated with the key inside the cache
             Cacheable object = null;
             synchronized ( cacheHashMap )  {
                object = (Cacheable)cacheHashMap.get(key);
             status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>"  );
             status += ( "<br>���<b>Class�of:</b><i>" + object.toString() + "</i>");
             status += ( "<br>���<b> Expires at:</b><i>" + object.getExpireDate() + "</i>");
             status += ( "<br>���<b> Cache Hits:</b><i>" + object.getCacheHits().toString() + "</i>");
             status += ( "<br>���<b> Object Size:</b><i>" + object.getByteCount(object).toString() + "</i>");
             int bytesServed = object.getCacheHits().intValue() * object.getByteCount(object).intValue();
             double eff = 0.0;
             // handle divide by 0
             if ( bytesServed > 0 ) {
                eff = ( bytesServed - object.getByteCount(object).intValue() ) / bytesServed;
             status += ( "<br>���<b> Cache Efficiency:</b><i>" + eff + "</i><br><br>");
          status += ( "</body></html>" );
          return status;
       * Used to get a html page on the status of the cache
       public static String flushCache()
          Set keySet = null;
          Iterator keys = null;
          synchronized ( cacheHashMap )  {
             keySet = cacheHashMap.keySet();
             keys   = keySet.iterator();
          String status = new String();
          status += ( "<html><head>");
          status += ( "<meta http-equiv=\"Cache-Control\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Pragma\" content=\"no-cache\" />");
          status += ( "<meta http-equiv=\"Expires\" content=\"0\" /> ");
          status += ( "</head><body>" );
          status += ( "<p><h4>Cache status before cache reset " + (new java.util.Date()).toString() + "</h4>" );
          status += ( "<p>Cache size: " + getCount() + " object(s) cached" );
          status += ( "<p>Cache contains: " );
          while(keys.hasNext())
             Object key = keys.next();
             // Get the cacheable object associated with the key inside the cache
             Cacheable object = null;
             synchronized ( cacheHashMap )  {
                object = (Cacheable)cacheHashMap.get(key);
             status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>  <b>Class of:</b><i>" + object.toString() );
             status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
          CacheManager.emptyCache();
          status += ( "<p><h4>Cache status after cache reset " + (new java.util.Date()).toString() + "</h4>" );
          status += ( "<p>Cache size: " + CacheManager.getCount() + " object(s) cached" );
          status += ( "<p>Cache contains: " );
          Set newKeySet = null;
          Iterator newKeys = null;
          synchronized ( cacheHashMap )  {
             newKeySet = cacheHashMap.keySet();
             newKeys   = newKeySet.iterator();
          // this really never gets executed
          while(newKeys.hasNext())
             Object key = newKeys.next();
             // Get the cacheable object associated with the key inside the cache
             Cacheable object = null;
             synchronized ( cacheHashMap )  {
                object = (Cacheable)cacheHashMap.get(key);
             status += ( "<br><b>ID:</b><i>" + object.getIdentifier() + "</i>  <b>Class of:</b><i>" + object.toString() );
             status += ( "</i><b> Expires at:</b>" + object.getExpireDate() + "</i>");
          status += ( "</body></html>" );
          return status;

  • Java.util.logging - Problem with setting different Levels for each Handler

    Hello all,
    I am having issues setting up the java.util.logging system to use multiple handlers.
    I will paste the relevant code below, but basically I have 3 Handlers. One is a custom handler that opens a JOptionPane dialog with the specified error, the others are ConsoleHandler and FileHandler. I want Console and File to display ALL levels, and I want the custom handler to only display SEVERE levels.
    As it is now, all log levels are being displayed in the JOptionPane, and the Console is displaying duplicates.
    Here is the code that sets up the logger:
    logger = Logger.getLogger("lib.srr.applet");
    // I have tried both with and without the following statement          
    logger.setLevel(Level.ALL);
    // Log to file for all levels FINER and up
    FileHandler fh = new FileHandler("mylog.log");
    fh.setFormatter(new SimpleFormatter());
    fh.setLevel(Level.FINER);
    // Log to console for all levels FINER and up
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.FINER);
    // Log SEVERE levels to the User, through a JOptionPane message dialog
    SRRUserAlertHandler uah = new SRRUserAlertHandler();
    uah.setLevel(Level.SEVERE);
    uah.setFormatter(new SRRUserAlertFormatter());
    // Add handlers
    logger.addHandler(fh);
    logger.addHandler(ch);
    logger.addHandler(uah);
    logger.info(fh.getLevel().toString() + " -- " + ch.getLevel().toString() + " -- " + uah.getLevel().toString());
    logger.info("Logger Initialized.");Both of those logger.info() calls displays to the SRRUserAlertHandler, despite the level being set to SEVERE.
    The getLevel calls displays the proper levels: "FINER -- FINER -- SEVERE"
    When I start up the applet, I get the following in the console:
    Apr 28, 2009 12:01:34 PM lib.srr.applet.SRR initLogger
    INFO: FINER -- FINER -- SEVERE
    Apr 28, 2009 12:01:34 PM lib.srr.applet.SRR initLogger
    INFO: FINER -- FINER -- SEVERE
    Apr 28, 2009 12:01:40 PM lib.srr.applet.SRR initLogger
    INFO: Logger Initialized.
    Apr 28, 2009 12:01:40 PM lib.srr.applet.SRR initLogger
    INFO: Logger Initialized.
    Apr 28, 2009 12:01:41 PM lib.srr.applet.SRR init
    INFO: Preparing Helper Files.
    Apr 28, 2009 12:01:41 PM lib.srr.applet.SRR init
    INFO: Preparing Helper Files.
    Apr 28, 2009 12:01:42 PM lib.srr.applet.SRR init
    INFO: Getting PC Name.
    Apr 28, 2009 12:01:42 PM lib.srr.applet.SRR init
    INFO: Getting PC Name.
    Apr 28, 2009 12:01:42 PM lib.srr.applet.SRR init
    INFO: Finished Initialization.
    Apr 28, 2009 12:01:42 PM lib.srr.applet.SRR init
    INFO: Finished Initialization.Notice they all display twice. Each of those are also being displayed to the user through the JOptionPane dialogs.
    Any ideas how I can properly set this up to send ONLY SEVERE to the user, and FINER and up to the File/Console?
    Thanks!
    Edit:
    Just in case, here is the code for my SRRUserAlertHandler:
    public class SRRUserAlertHandler extends Handler {
         public void close() throws SecurityException {
         public void flush() {
         public void publish(LogRecord arg0) {
              JOptionPane.showMessageDialog(null, arg0.getMessage());
    }Edited by: compbry15 on Apr 28, 2009 9:44 AM

    For now I have fixed the issue of setLevel not working by making a Filter class:
    public class SRRUserAlertFilter implements Filter {
         public boolean isLoggable(LogRecord arg0) {
              if (arg0.getLevel().intValue() >= Level.WARNING.intValue()) {
                   System.err.println(arg0.getLevel().intValue() + " -- " + Level.WARNING.intValue());
                   return true;
              return false;
    }My new SRRUserAlertHandler goes like this now:
    public class SRRUserAlertHandler extends Handler {
         public void close() throws SecurityException {
         public void flush() {
         public void publish(LogRecord arg0) {
              Filter theFilter = this.getFilter();
              if (theFilter.isLoggable(arg0))
                   JOptionPane.showMessageDialog(null, arg0.getMessage());
    }This is ugly as sin .. but I cannot be required to change an external config file when this is going in an applet.
    After much searching around, this logging api is quite annoying at times. I have seen numerous other people run into problems with it not logging specific levels, or logging too many levels, etc. A developer should be able to complete configure the system without having to modify external config files.
    Does anyone else have another solution?

  • How to set property "java.util.Arrays.useLegacyMergeSort" in jnlp-file?

    Hi,
    I have a problem in a web start application with java 7 and the new sort behavior (exception: comparison method violates its general contract).
    So I like to go back to previous behavior and tried to put the new java 7 system property "java.util.Arrays.useLegacyMergeSort" in the generated jnlp-File:
    <property name="java.util.Arrays.useLegacyMergeSort" value="true"/>.
    Now I can read the property value in java code with System.getProperty("java.util.Arrays.useLegacyMergeSort"), and guess the property was successful set, but the exception still appears?!
    The system property works with command line "javaws -J-Djava.util.Arrays.useLegacyMergeSort=true file.jnlp", but not via doubleclick on the jnlp-file or url and browser.
    Any ideas?
    Cheers,
    Dan

    Only "trusted" set of properties can be set in the JNLP file by unsigned applications.
    List of properties is revised from time to time but it usually takes time for new properties to be added to it (if there is strong demand for it as every property should undergo security audit).
    You can specify arbitrary property if you sign your application and JNLP file.

  • Unable to set WEEK_OF_YEAR in java.util.Calender

    in java.util.Calender unable to set WEEK_OF_YEAR, it takes only the current month for any year
    could anyone give a solution

    hi there,
    try this:
    Calendar calendar = Calendar.getInstance();
    System.out.println("current week of the year is: " + calendar.get(cal.WEEK_OF_YEAR));
    System.out.println(cal.getTime());
    calendar.set(cal.WEEK_OF_YEAR, 32);
    System.out.println("week of the year is now: " + calendar.get(cal.WEEK_OF_YEAR));
    System.out.println(cal.getTime());
    hope this helps,
    PSChan
    Sun Microsystems

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Doubt in java.util.logging

    Hi,
    I have doubt in logging api provided in java 1.4.
    I have a simple program to get the logger and output log into it.
    This is how the program looks.
    LogTest.java
    import java.util.logging.*;
    import java.util.*;
    public class LogTest {
    public static void main(String args[]) {
         LogManager manager = LogManager.getLogManager();
         Logger l = manager.getLogger("global");
         System.out.println(l);
         l.severe("Test");
         System.out.println(manager.getLogger("ivy"));
         System.out.println(manager.getLogger("test"));
    I able to get the instance of the global logger, but im not able to get instance of other logger. I getting null for all the other logger
    test.properites
    =================
    handlers = java.util.logging.ConsoleHandler
    java.util.logging.ConsoleHandler.level=INFO
    java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
    ivy.level = INFO
    .ivy.level = INFO
    =================
    Compilation Command
    java -Djava.util.logging.config.file=C:\WorkSpace\test.properties LogTest Output:
    java.util.logging.Logger@13f5d07
    Jan 25, 2006 7:19:24 PM LogTest main
    SEVERE: Test
    null
    null
    I also tried the same with no config properties, Still im getting the null for logger.
    Can I know is there anything that im missing. Is there any property that must be set or do i hav set some config properties.
    Thanks,
    Siva

    Well, basically that's part of the formatdefinition
    that Properties uses. If you don't do it, then you
    aren't really using Properties format and you'llhave
    to do your own IO.Thanks for the reply. Is there anyother api or class
    that can be used to resolve my problem.What is the problem? A character is escaped, but you will get : when you read the value. You don't have a problem as long as all reading / writing is done through that class.

Maybe you are looking for