1 Reply Latest reply on May 31, 2007 9:54 AM by Manik Surtani

    Recommended way of locking to avoid many threads filling cac

    Marius Kotsbak Newbie

      I have this case as this pseudocode shows:

      1: if ( jbc.get( "someobj" ) == null || cache error ) {
      2: obj = getSomeObjFromDB();
      3: jbc.put("someojb).

      4: return obj;

      and typically have many threads accessing that method from JBoss at the same time. The problem is that line 2 can be time consuming and thus both:

      - causing write locks in JBC for all but the first thread that got the write lock at line 3. This is probably similar to the Hibernate case and thus can probably avoided using the new "putFromExternalRead()" method?

      - cause n number of threads simultaniously trying to get the same value from database (line 2) that both slows down the first one that has the write lock and all other.

      What I want to solve those problems are some kind of lock that ensures that only the first thread that finds the cache miss fetches the object from the database and the others wait for that first thread to finish its fetching and then getting the value from JBC.

      Since this is running inside JBoss I'm not sure what locking is safe to use. In a standalone program I would think of using a mutex or synchcronized keyword, but is this safe in this case?

      I also think about a little hacky solution to use an extra node in JBC that you write to before fetching stuff from DB and the other threads lock on trying to write to and after the lock is freed check again if the content is still missing and if so (it in fact was the first thread) go fetch it from DB.

      Maybe the API of JBC should be added with some support for this to do in it a clean way.