Class SubjectRunnable

  • All Implemented Interfaces:

    public class SubjectRunnable
    extends Object
    implements Runnable
    A SubjectRunnable ensures that a target/delegate Runnable will execute such that any call to SecurityUtils.getSubject() during the Runnable's execution will return the associated Subject instance. The SubjectRunnable instance can be run on any thread (the current thread or asynchronously on another thread) and the SecurityUtils.getSubject() call will still work properly. This implementation also guarantees that Shiro's thread state will be identical before and after execution to ensure threads remain clean in any thread-pooled environment.

    When instances of this class run(), the following occurs:

    1. The Subject and any of its associated thread state is first bound to the thread that executes the Runnable.
    2. The delegate/target Runnable is run
    3. Any previous thread state that might have existed before the Subject was bound is fully restored


    This is typically considered a support class and is not often directly referenced. Most people prefer to use the Subject.execute or Subject.associateWith methods, which transparently perform the necessary association logic.

    An even more convenient alternative is to use a SubjectAwareExecutor, which transparently uses instances of this class but does not require referencing Shiro's API at all.

    See Also:
    Subject.associateWith(Runnable), SubjectAwareExecutor
    • Constructor Detail

      • SubjectRunnable

        public SubjectRunnable​(Subject subject,
                               Runnable delegate)
        Creates a new SubjectRunnable that, when executed, will execute the target delegate, but guarantees that it will run associated with the specified Subject.
        subject - the Subject to associate with the delegate's execution.
        delegate - the runnable to run.
    • Method Detail

      • run

        public void run()
        Binds the Subject thread state, executes the target Runnable and then guarantees the previous thread state's restoration:
         try {
         } finally {
        Specified by:
        run in interface Runnable
      • doRun

        protected void doRun​(Runnable runnable)
        Simply calls the target Runnable's run() method.
        runnable - the target runnable to run.