6 Replies Latest reply on Feb 23, 2005 2:10 PM by krisjenkins

    Atomic read OR write

    krisjenkins

      Hi,

      I'm looking into migrating from OSCache to JBossCache, and I'm worried about a locking issue.

      I'd like to be able to say, atomically, "Read this FQN/KEY, and if it comes back null, acquire a write lock and query the database". What I want to avoid is having two threads which read, find the key empty, first thread aquires a write lock, second thread queues for a write lock when it will only need a read lock.

      Is it possible to do this with JBossCache?

      Cheers,
      Kris

        • 1. Re: Atomic read OR write

          This may be difficult to do without thinking it further. If the node does not exist, for example, there is no way to lock it. Therefore, atomicity can not be achieved.

          -Ben

          • 2. Re: Atomic read OR write
            belaban

            How about the following code:

            // ReentrantLock lock;
            lock.acquire();
            Object val=cache.get(key);
            if(val == null) {
            val=fetchValueFromDB();
            cache.put(node, key, val);
            }
            lock.release();

            This simply uses external synchronization.

            A more elegant solution would be to use a CacheLoader: a get() fetches the value from the DB and adds it to the cache with a write-lock. CacheLoader synchronizes access, so only 1 thread actually triggers the loading.

            • 3. Re: Atomic read OR write
              krisjenkins

              Ah, that's a shame. Thanks for the rapid answer though, Ben.

              Cheers,
              Kris

              • 4. Re: Atomic read OR write
                krisjenkins

                Bela,

                Maybe I'm missing something, but it looks like that code fragment makes things worse. Now it will synchronize on every read, not just every read-that-requires-a-write. Is that right? And if so, would a cacheLoader suffer the same problem?

                Kris



                • 5. Re: Atomic read OR write
                  belaban

                  Use a read/write lock then. The problem you are trying to solve is exactly what the CacheLoader was designed to do.

                  With a CacheLoader, every get() on a non-existing node, or a node marked as not-yet-loaded will access the underlying store.

                  • 6. Re: Atomic read OR write
                    krisjenkins

                    I see. Thanks Bela. :-)