一位同事指出了
Log4J 2.3 code的以下片段:
/** * Called to determine if the configuration has changed. */ @Override public void checkConfiguration() { final long current = System.currentTimeMillis(); if (((counter.incrementAndGet() & MASK) == 0) && (current >= nextCheck)) { LOCK.lock(); try { nextCheck = current + intervalSeconds; if (file.lastModified() > lastModified) { lastModified = file.lastModified(); for (final ConfigurationListener listener : listeners) { final Thread thread = new Thread(new ReconfigurationWorker(listener,reconfigurable)); thread.setDaemon(true); thread.start(); } } } finally { LOCK.unlock(); } }
其中counter是AtomicInteger字段,MASK设置为0x0f,nextCheck为long.
据我所知,此方法检查是否重新加载配置,但仅当计数器的值可被16整除并且下一个配置检查周期已过时才会这样做.
为什么这是按位和那里?
鉴于对于计数器实例,incrementAndGet是同步的,它可以被认为是“廉价”的限制机制吗?或者也许在“典型”nextCheck周期期间调用checkConfiguration的次数超过必要的次数,因此按位AND作为性能技巧(再次,限制?).