public int allocate_id (Object object) {
    /* From XC-MISC extension specification:
     * 
     * When an X client connects to an X server, it receives a fixed range
     * of resource IDs to use to identify the client's resources inside the
     * X server. Xlib hands these out sequentially as needed. When it
     * overruns the end of the range, an IDChoice protocol error results. 
     * Long running clients, or clients that use resource IDs at a rapid
     * rate, may encounter this circumstance. When it happens, there are
     * usually many resource IDs available, but Xlib doesn't know about
     * them.
     *
     * One approach to solving this problem would be to have Xlib notice
     * when a resource is freed and recycle its ID for future use. This
     * strategy runs into difficulties because sometimes freeing one
     * resource causes others to be freed (for example, when a window is
     * destroyed, so are its children). To do a complete job, Xlib would
     * have to maintain a large amount of state that currently resides only
     * in the server (the entire window tree in the above example). Even if
     * a less comprehensive strategy was adopted, such as recycling only
     * those IDs that Xlib can identify without maintaining additional
     * state, the additional bookkeeping at resource creation and
     * destruction time would likely introduce unacceptable overhead.
     *
     * To avoid the problems listed above, the server's complete knowledge
     * of all resource IDs in use by a client is leveraged. This extension
     * provides two ways for Xlib to query the server for available
     * resource IDs. Xlib can use these extension requests behind the
     * scenes when it has exhausted its current pool of resource IDs.
     */

    /* If XC-MISC is present, we use it. Otherwise, we fall back to
     * allocate X resource ID sequentially to the end without recycling ID
     * (just as xlib does).
     *
     * Sample values:
     *   resource base: 0x04000000 or 00000100000000000000000000000000b
     *   resource mask: 0x003FFFFF or 00000000001111111111111111111111b
     */

    if (!use_xcmisc)
      // check if basic allocation fails
      use_xcmisc = (resource_index+1 & ~resource_mask) != 0;


    if (!use_xcmisc) {
      int id = resource_index++ | resource_base;
      resources.put (new Integer (id), object);
      return id;
    }

    
    if (xcmisc == null) 
      try {
        xcmisc = new XCMisc (this);
      } catch (NotFoundException e) {
        throw new RuntimeException ("Failed to allocate new resource id");
      }

    
    if (xcmisc_resource_count == 0) {
      // first time, or used up
      gnu.x11.extension.XCMisc.XIDRange rr = xcmisc.xid_range ();
      xcmisc_resource_base = rr.start_id;
      xcmisc_resource_count = rr.count;
    }

    
    // give out in descending order
    xcmisc_resource_count--;
    return xcmisc_resource_base+xcmisc_resource_count;   
  }