Java API token expiration handler
useToken

I don't really get your expected behavior from this method. You only retry when expired, what if an exception occured while not yet expired? Nothing happens, not even a log. The same with exceptions that occur when retryWhenTokenExpired is not set, the exception gets swallowed without any trace. 


  catch (Exception e) {
    if (retryWhenTokenExpired &amp;&amp; tokenExpired(e.getMessage())) {
        System.out.println("token expired, retry");
        resetToken();
        useToken(tokenConsumer, false);
    }
  }



I would make sure the following constraint is true: either a retry is performed or an exception is propagated up the stack. In addition, on expiration, reset the token when requested so. log is an abstraction of your System.out.println.

  catch (Exception e) {
    log("error using token: " + e.getMessage());
    if (!retryWhenTokenExpired) {
        throw e;
    }
    final boolean expired = tokenExpired(e.getMessage());
    if (expired) {
        log("token expired, retry");
        resetToken();
    }
    useToken(tokenConsumer, !expired);
  }