示例:
public class WxMessageInMemoryDuplicateChecker {
private final Long timeToLive;
private final Long clearPeriod;
private final ConcurrentHashMap< String, Long> msgId2Timestamp = new ConcurrentHashMap < > ( ) ;
private final AtomicBoolean backgroundProcessStarted = new AtomicBoolean ( false ) ;
protected void checkBackgroundProcessStarted ( ) {
if ( this . backgroundProcessStarted. getAndSet ( true ) ) {
return ;
}
Thread t = new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
try {
while ( true ) {
Thread. sleep ( WxMessageInMemoryDuplicateChecker. this . clearPeriod) ;
Long now = System. currentTimeMillis ( ) ;
for ( Map. Entry< String, Long> entry :
WxMessageInMemoryDuplicateChecker. this . msgId2Timestamp. entrySet ( ) ) {
if ( now - entry. getValue ( ) > WxMessageInMemoryDuplicateChecker. this . timeToLive) {
WxMessageInMemoryDuplicateChecker. this . msgId2Timestamp. entrySet ( ) . remove ( entry) ;
}
}
}
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
} ) ;
t. setDaemon ( true ) ;
t. start ( ) ;
}
}