DefaultRetryPolicy.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.qingdaofushan.home.downloadmanager;
  2. /**
  3. * Created by maniselvaraj on 15/4/15.
  4. */
  5. public class DefaultRetryPolicy implements RetryPolicy {
  6. /** The current timeout in milliseconds. */
  7. private int mCurrentTimeoutMs;
  8. /** The current retry count. */
  9. private int mCurrentRetryCount;
  10. /** The maximum number of attempts. */
  11. private final int mMaxNumRetries;
  12. /** The backoff multiplier for for the policy. */
  13. private final float mBackoffMultiplier;
  14. /** The default socket timeout in milliseconds */
  15. public static final int DEFAULT_TIMEOUT_MS = 5000;
  16. /** The default number of retries */
  17. public static final int DEFAULT_MAX_RETRIES = 1;
  18. /** The default backoff multiplier */
  19. public static final float DEFAULT_BACKOFF_MULT = 1f;
  20. /**
  21. * Constructs a new retry policy using the default timeouts.
  22. */
  23. public DefaultRetryPolicy() {
  24. this(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT);
  25. }
  26. /**
  27. * Constructs a new retry policy.
  28. * @param initialTimeoutMs The initial timeout for the policy.
  29. * @param maxNumRetries The maximum number of retries.
  30. * @param backoffMultiplier Backoff multiplier for the policy.
  31. */
  32. public DefaultRetryPolicy(int initialTimeoutMs, int maxNumRetries, float backoffMultiplier) {
  33. mCurrentTimeoutMs = initialTimeoutMs;
  34. mMaxNumRetries = maxNumRetries;
  35. mBackoffMultiplier = backoffMultiplier;
  36. }
  37. @Override
  38. public float getBackOffMultiplier() {
  39. return mBackoffMultiplier;
  40. }
  41. @Override
  42. public int getCurrentTimeout() {
  43. return mCurrentTimeoutMs;
  44. }
  45. @Override
  46. public int getCurrentRetryCount() {
  47. return mCurrentRetryCount;
  48. }
  49. @Override
  50. public void retry() throws RetryError {
  51. mCurrentRetryCount++;
  52. mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);
  53. if (!hasAttemptRemaining()) {
  54. throw new RetryError();
  55. }
  56. }
  57. /**
  58. * Returns true if this policy has attempts remaining, false otherwise.
  59. */
  60. protected boolean hasAttemptRemaining() {
  61. return mCurrentRetryCount <= mMaxNumRetries;
  62. }
  63. }