SpringRetry线程安全设计
一、重试上下文缓存
对各种策略的上下文进行了缓存,接口如下:

实现类有两:

默认使用MapRetryContextCache方式;
打开源码:

其持有了一个线程安全的Map对象用于实现多线程环境下各个线程的上下文缓存线程安全,同时避免频繁创建上下文对象,提高性能;
这个上下文缓存Map对象主要使用在RestTemplate中,用于多线环境下各个线程的重试上下文在线程内的传递预共享,主要使用在RetryCallback和RecoveryCallback传递用于自定义对象;
二、RestTemplate之上下文管理器
当执行过程中从上下文缓存中拿不到上下文的缓存对象时候,


注意这里的RetrySynchronizationManager,这个就是我们重试上下文管理器,命名RetrySynchronizationContextManager这个更合适,打开源码发现持有一个final的ThreadLocal对象,通过该方法实现线程安全;
官方描述:
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
三、回退策略之synchronized修饰符
ExponentialBackOffPolicy 指数级回退策略中对指数增加的下一次Sleep进行synchronized同步计算,实现线程安全

网友评论