简体   繁体   English

Java:做静态HTTP请求是一种好习惯吗?

[英]Java: Is it good practice to do static HTTP Requests?

I just had a discussion with a colleague who asked me why i would do a static Http request like this: 我刚刚和一位同事讨论过,他问我为什么我会像这样执行静态Http请求:

HttpClient.doGet(HashMap<String,String> Parameters);

instead of invoking an object of the class via default constructor and use a nonstatic method like this: 而不是通过默认构造函数调用该类的对象,而是使用这样的非静态方法:

new HttpClient().doGet(HashMap<String,String> Parameters)

If assuming that the implementation of the method doGet only uses the parameters of the function without any member variables, would the static implementation be problematic in any way, eg thread safety? 如果假设方法doGet的实现仅使用函数的参数而没有任何成员变量,那么静态实现是否会在任何方面带来问题,例如线程安全?

It depends on what you mean by problematic, but going off just your given example, the answer is no, the static method call is not problematic, and is arguably better, since no object needs to be instantiated. 这取决于问题的含义,但是仅给出示例即可,答案是否定的,静态方法调用没有问题,而且可以说是更好的方法,因为不需要实例化任何对象。

You mentioned thread safety, so I will touch on that. 您提到了线程安全性,因此我将对此进行说明。 You only need to be concered with thread safety if there is "mutable shared state" involved. 如果涉及“可变共享状态”,则只需要考虑线程安全。 Mutable being the key-word here. Mutable是这里的关键词。 For example, if multiple threads were sharing the same instance of HttpClient, and that HttpClient was keeping track of some state by mutating one or more of its member variables, then that definitely has the potential to be problematic. 例如,如果多个线程共享同一个HttpClient实例,并且该HttpClient通过更改其一个或多个成员变量来跟踪某个状态,那么这肯定有问题的可能性。

... but also, every HTTP request has to go out on a network, to a physical computer someplace else, then to return, "at least many milli- seconds later." ...而且,每个HTTP请求都必须在网络上发送到其他地方的物理计算机,然后“至少在几毫秒后”返回。 So, there's really no point in "multi-threading" that chore. 因此,“多线程” 这一琐事真的没有意义。 A single thread can be given the responsibility for sending out parallel I/O-requests to the remote hosts, receiving requests from the rest of your code by means of some thread-safe queue and returning the responses in like manner on another queue (or, queues). 可以让单个线程负责向远程主机发出并行I / O请求,通过一些线程安全队列从其余代码接收请求,并以类似的方式在另一个队列中返回响应(或,队列)。

It is wasteful to associate "a thread" with "a request." 将“线程”与“请求”相关联是浪费的。 A very small pool of workers can be consuming the responses that come off of that reply-queue. 很少的工作人员会消耗掉来自该答复队列的响应。

(And of course, there are plenty of existing Java open-source frameworks that implement all of this very-familiar plumbing for you.) (当然,有很多现有的Java开源框架可以为您实现所有这些非常熟悉的管道。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM