使用ThreadPoolExecutor和DiscardPolicy [英] Using ThreadPoolExecutor and DiscardPolicy

查看:860
本文介绍了使用ThreadPoolExecutor和DiscardPolicy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用ThreadPoolExecutor来建立客户端队列,并且如果它超过某个数字(例如5),则必须删除客户端.这是一种DDOS保护.当客户端#6请求我的服务器时-它被丢弃,等等.我得到了服务器和客户端代码,但是我不知道如何实现ThreadPoolExecutor和DiscardPolicy.想法或例子?

I need to make a client queue with ThreadPoolExecutor and an ability to drop clients if it exceeds some number (5 for example). It is kinda DDOS protection. When client #6 is requesting my server - it got dropped, etc. I got my server and client code, but I don't know how to realize ThreadPoolExecutor and DiscardPolicy. Ideas or examples?

简单服务器:

   import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Semaphore;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class Server {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        ServerSocket server = new ServerSocket (3000);

        ExecutorService es = Executors.newFixedThreadPool(2);

        Semaphore semaphore = new Semaphore (2);

        while(true){

        semaphore.acquire();

        Socket accept2 = server.accept();

        es.execute(()->{
            try (Socket accept = accept2) {
            serve(accept);
            } catch (Exception exception) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, exception);
            } 
            finally {
                semaphore.release();

            }
        });        

        }

    }

    private static void serve(final Socket accept) throws ClassNotFoundException, IOException {
        InputStream inputStream = accept.getInputStream();
        OutputStream outputStream = accept.getOutputStream();

        ObjectInputStream inputStream2 = new ObjectInputStream (inputStream);

        while (true){
            Object readObject = inputStream2.readObject();
            System.out.println(readObject);
        }

        }

    }

还有一个简单的客户端:

And a simple client:

  import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.net.Socket;

    public class Client {

    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = new Socket ("localhost", 3000);
        ObjectOutputStream oos = new ObjectOutputStream (
                socket.getOutputStream());
        oos.writeObject("First!");
        Thread.sleep(10000);
        oos.writeObject("First again!");
        Thread.sleep(10000);
        oos.writeObject("First again again!");

        }

    }

推荐答案

ThreadPoolExecutorDiscardPolicy一起使用,如下所示:

Use ThreadPoolExecutor with DiscardPolicy as below:

  int poolSize=1;
  int maxPoolSize=2;
  int queueSize=5;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  ThreadPoolExecutor executor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                    TimeUnit.MILLISECONDS,queue,new ThreadPoolExecutor.DiscardPolicy());
}

被拒绝的任务:

在执行器已关闭时,并且在执行器对最大线程数和工作队列容量使用有限范围且已饱和时,将拒绝在方法execute(Runnable)中提交的新任务.

New tasks submitted in method execute(Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated.

在任何一种情况下,execute方法都会调用其RejectedExecutionHandlerRejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor)方法.

In either case, the execute method invokes the RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor) method of its RejectedExecutionHandler.

提供了四个预定义的处理程序策略:

Four predefined handler policies are provided:

  1. 在默认的ThreadPoolExecutor.AbortPolicy中,处理程序在拒绝时会抛出运行时RejectedExecutionException.
  2. ThreadPoolExecutor.CallerRunsPolicy中,调用的线程执行自身运行该任务.这提供了一种简单的反馈控制机制,可以降低新任务的提交速度.
  3. ThreadPoolExecutor.DiscardPolicy中,简单地删除了无法执行的任务.
  4. ThreadPoolExecutor.DiscardOldestPolicy中,如果未关闭执行程序,则将丢弃工作队列开头的任务,然后重试执行(该操作可能再次失败,从而导致重复执行此操作).
  1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.
  2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
  3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.
  4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

看看此文档页面以获取更多详细信息

Have a look at this documentation page for more details

这篇关于使用ThreadPoolExecutor和DiscardPolicy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆