这个接口用于将线程执行中的对象绑定到线程上或者在某些时候将不需要的对象从线程上解绑定。
bind方法:将对象绑定到对象上方便以后的调用。
Resotore方法:在线程结束之后如果是抛了异常之后,线程必须回复成原来的样子,这样可以保证线程在重复使用的时候的干净调用,放置出错。这个方法比最好用try finally的方式调用。
书写格式例子
ThreadState state = // try{ state.bind(); dosomething(); }finally{ state.restore(); }
他得实现类:SubjectThreadState用于将subject绑定到线程上,方便使用securityUtils.getSubject()的调用。
方法:bind():
publicvoid bind() { SecurityManager securityManager = this.securityManager; if ( securityManager == null ) { //try just in case the constructor didn't find one at the time: securityManager = ThreadContext.getSecurityManager(); } this.originalResources = ThreadContext.getResources();//将之前的信息存起来。 ThreadContext.remove();//清空之前的信息 ThreadContext.bind(this.subject);//重新绑定subject。 if (securityManager != null) { ThreadContext.bind(securityManager);//重新绑定securityManager。 } }
Restore方法
publicvoid restore() { ThreadContext.remove();//将之前通过调用bind方法添加的内容情况, if (!CollectionUtils.isEmpty(this.originalResources)) { ThreadContext.setResources(this.originalResources);//再将之前在bind方法中保存的信息回复到当前线程。使当前线程能继续使用 } }
总结一句话:这个类用于线程的重复使用,先将之前的信息存储起来,然后绑定subject + securityManager,最后再重新回复线程的信息,使其能够重复使用。