有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果未收到数据,java是否发送并重试数据?

我正在从事一个项目,我需要做以下事情:

  • 将特定socket上的特定数据发送到另一个系统。我必须在给定的socket上发送一个特定的字节数组。每个字节数组都有一个唯一的长地址
  • 然后使用下面实现的RetryStrategy之一继续尝试发送相同的数据
  • 启动一个后台轮询线程,告诉您发送的数据是否在其他系统中收到。如果它被接收到,那么我们将从pending队列中删除它,这样它就不会被重试。如果出于任何原因它没有被接收到,那么我们将使用我们使用的RetryStrategy再次尝试发送相同的数据

例如:如果我们发送了byteArrayA,它的唯一长地址为addressA,并且如果它是在另一个系统中接收到的,那么我的轮询器线程将把这个addressA作为确认返回,这意味着它已被接收,所以现在我们可以从挂起队列中删除这个地址,这样它就不会再次被重试

我有两个{}实现{}和{}。所以我设计了下面的模拟器来模拟上面的流程

public class Experimental {
  /** Return the desired backoff delay in millis for the given retry number, which is 1-based. */
  interface RetryStrategy {
    long getDelayMs(int retry);
  }

  public enum ConstantBackoff implements RetryStrategy {
    INSTANCE;
    @Override
    public long getDelayMs(int retry) {
      return 1000L;
    }
  }

  public enum ExponentialBackoff implements RetryStrategy {
    INSTANCE;
    @Override
    public long getDelayMs(int retry) {
      return 100 + (1L << retry);
    }
  }

  /** A container that sends messages with retries. */    
  private static class Sender {
    private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(20);
    private final ConcurrentMap<Long, Retrier> pending = new ConcurrentHashMap<>();

    /** Send the given (simulated) data with given address on the given socket. */
    void sendTo(long addr, byte[] data, int socket) {
      System.err.println("Sending " + Arrays.toString(data) + "@" + addr + " on " + socket);
    }

    /** The state of a message that's being retried. */
    private class Retrier implements Runnable {
      private final RetryStrategy retryStrategy;
      private final long addr;
      private final byte[] data;
      private final int socket;
      private int retry;
      private Future<?> future;

      Retrier(RetryStrategy retryStrategy, long addr, byte[] data, int socket) {
        this.retryStrategy = retryStrategy;
        this.addr = addr;
        this.data = data;
        this.socket = socket;
        this.retry = 0;
      }

      private synchronized void start() {
        if (future == null) {
          future = executorService.submit(this);
          pending.put(addr, this);
        }
      }

      private synchronized void cancel() {
        if (future != null) {
          future.cancel(true);
          future = null;
        }
      }

      private synchronized void reschedule() {
        if (future != null) {
          future = executorService.schedule(this, retryStrategy.getDelayMs(++retry), MILLISECONDS);
        }
      }

      @Override
      synchronized public void run() {
        sendTo(addr, data, socket);
        reschedule();
      }
    }

   /** 
    * Get a (simulated) verified message address. Just picks a pending 
    * one. Returns zero if none left.
    */      
    long getVerifiedAddr() {
      System.err.println("Pending messages: " + pending.size());
      Iterator<Long> i = pending.keySet().iterator();
      long addr = i.hasNext() ? i.next() : 0;
      return addr;
    }

    /** A polling loop that cancels retries of (simulated) verified messages. */        
    class CancellationPoller implements Runnable {
      @Override
      public void run() {
        while (!Thread.currentThread().isInterrupted()) {
          try {
            Thread.sleep(1000);
          } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
          }
          long addr = getVerifiedAddr();
          if (addr == 0) {
            continue;
          }
          System.err.println("Verified message (to be cancelled) " + addr);
          Retrier retrier = pending.remove(addr);
          if (retrier != null) {
            retrier.cancel();
          }
        }
      }
    }

    private Sender initialize() {
      executorService.submit(new CancellationPoller());
      return this;
    }

    private void sendWithRetriesTo(RetryStrategy retryStrategy, long addr, byte[] data, int socket) {
      new Retrier(retryStrategy, addr, data, socket).start();
    }
  }

  public static void main(String[] args) {
    Sender sender = new Sender().initialize();
    for (long i = 1; i <= 10; i++) {
      sender.sendWithRetriesTo(ConstantBackoff.INSTANCE, i, null, 42);
    }
    for (long i = -1; i >= -10; i--) {
      sender.sendWithRetriesTo(ExponentialBackoff.INSTANCE, i, null, 37);
    }
  }
}

我想看看上面的代码中是否存在任何争用条件或线程安全问题?因为在多线程中正确处理内容是很困难的

让我知道是否有更好或有效的方法来做同样的事情


共 (1) 个答案

  1. # 1 楼答案

    如果您的代码中没有针对第三方库的内容,那么您可以看看这个https://github.com/nurkiewicz/async-retry。假设我正确理解了您的问题,此库允许您在不重新发明轮子的情况下处理此类问题。它写得很清楚,而且有很好的文档记录,所以我希望你能找到自己的路。:)