1

这个 Java 缓存可以更安全或更快吗?

public class Cache {
    private long lastupdateTime = 0L;
    private String cachedData = null;
    public String getData() {
        long now = System.currentTimeMillis();
        if (now - lastupdateTime < 30000) {
            return cachedData;
        }
        else {
            synchronized (this) {
                if (now - lastupdateTime < 30000) {
                    return cachedData;
                }
                else {
                    lastupdateTime = now;
                    cachedData = getDataFromDatabase();
                    return cachedData;
                }
            }
        }
    }
    private String getDataFromDatabase() { ... }
}
4

3 回答 3

2

是的。即使忽略了你没有制造lastupdateTimecachedData挥发的事实,

                lastupdateTime = now;
                cachedData = getDataFromDatabase();

出现故障。
如果getDataFromDatabase因异常而失败,您将已经更新lastupdateTime,因此将继续返回 30 秒内的陈旧数据,null如果getDataFromDatabase第一次尝试失败则可能返回。

lastUpdateTime通过初始化到,您不会有任何损失Long.MIN_VALUE,并且会在时钟已向后设置的系统上更可靠地工作。

System.getCurrentTimeMillis可以倒退,这不太可能影响 30 秒的缓存,但对于这个用例,真的没有理由不使用它System.nanoTime()

于 2013-08-28T21:58:26.400 回答
1

这是一个想法 - 原则上synchronized是一种陈旧且低效的机制。

这里我用一个AtomicReference<Phaser>来表示缓存正在被更新。可Phaser用于等待更新完成。

public class Test {

  public static class Cache {
    // Cache timeout.
    private static final long Timeout = 10000;
    // Last time we updated.
    private volatile long lastupdateTime = 0L;
    // The cached data.
    private volatile String cachedData = null;
    // Cache is in the progress of updating.
    private AtomicReference<Phaser> updating = new AtomicReference<>();
    // The next Phaser to use - avoids unnecessary Phaser creation.
    private Phaser nextPhaser = new Phaser(1);

    public String getData() {
      // Do this just once.
      long now = System.currentTimeMillis();
      // Watch for expiry.
      if (now - lastupdateTime > Timeout) {
        // Make sure only one thread updates.
        if (updating.compareAndSet(null, nextPhaser)) {
          // We are the unique thread that gets to do the updating.
          System.out.println(Thread.currentThread().getName() + " - Get ...");
          // Get my new cache data.
          cachedData = getDataFromDatabase();
          lastupdateTime = now;
          // Make the Phaser to use next time - avoids unnecessary creations.
          nextPhaser = new Phaser(1);
          // Get the queue and clear it - there cannot be any new joiners after this.
          Phaser queue = updating.getAndSet(null);
          // Inform everyone who is waiting that they can go.
          queue.arriveAndDeregister();
        } else {
          // Wait in the queue.
          Phaser queue = updating.get();
          if (queue != null) {
            // Wait for it.
            queue.register();
            System.out.println(Thread.currentThread().getName() + " - Waiting ...");
            queue.arriveAndAwaitAdvance();
            System.out.println(Thread.currentThread().getName() + " - Back");
          }
        }
      }
      // Let them have the correct data.
      return cachedData;
    }

    private String getDataFromDatabase() {
      try {
        // Deliberately wait for a bit.
        Thread.sleep(5000);
      } catch (InterruptedException ex) {
        // Ignore.
      }
      System.out.println(Thread.currentThread().getName() + " - Hello");
      return "Hello";
    }
  }

  public void test() throws InterruptedException {
    System.out.println("Hello");
    // Start time.
    final long start = System.currentTimeMillis();
    // Make a Cache.
    final Cache c = new Cache();
    // Make some threads.
    for (int i = 0; i < 20; i++) {
      Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
          while (System.currentTimeMillis() - start < 60000) {
            c.getData();
            try {
              Thread.sleep(500);
            } catch (InterruptedException ex) {
              // Ignore.
            }
          }
        }
      });
      t.setName("Thread - " + i);
      t.start();
      // Stagger the threads.
      Thread.sleep(300);
    }
  }

  public static void main(String args[]) throws InterruptedException {
    new Test().test();
  }
}

请注意,这是我第一次使用Phaser- 我希望我做对了。

请注意,如果超时时间长于从数据库获取数据所需的时间,则此算法可能会失败。

于 2013-08-28T22:03:40.647 回答
0

您的Cash类具有两个共享*可变* 状态,lastupdateTime并且可以由两个不同的线程同时调用,它使用对其他线程可见的局部变量(位于cachedDatagetData()nowstack

怎么了 ?

  • 首先 if (now - lastupdateTime < 30000) { return cachedData;},其他线程可以看到和stale上的数据(您正在访问一个没有同步保证的共享可变状态)lastupdateTimecachedData

  • now变量形式这样一个不变量lastupdateTime所以now - lastupdateTime应该在一个Atomic Block

我能做些什么 ?

只需 make method synchronized,并使您的类完全线程安全

public class Cache {
    private long lastupdateTime = 0L;
    private String cachedData = null;
    public synchronized String getData() {
           long now = System.currentTimeMillis()
           if (nano - lastupdateTime < 30000) {
                return cachedData;
           }
           else {
               lastupdateTime = now;
               cachedData = getDataFromDatabase();
               return cachedData;
           }                
    }
    private String getDataFromDatabase() { ... }
}
于 2013-08-28T23:12:04.773 回答