惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
月光博客
月光博客
博客园 - Franky
Martin Fowler
Martin Fowler
U
Unit 42
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
The Cloudflare Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
J
Java Code Geeks
B
Blog RSS Feed
博客园 - 三生石上(FineUI控件)
MongoDB | Blog
MongoDB | Blog
腾讯CDC
博客园_首页
博客园 - 司徒正美
D
DataBreaches.Net
I
InfoQ
GbyAI
GbyAI
IT之家
IT之家
罗磊的独立博客

ashishb.net

A day in Luxembourg - the richest country in the world I was asked to install malware during a fake interview Book summary: Breakneck - China's quest to engineer the future by Dan Wang Book summary: How to Teach Your Baby to Read Book Summary: The Discontented Little Baby Book by Pamela Douglas Introducing Amazing Sandbox - run third-party tools and AI agents securely on your machine Why software outsourcing gets a bad reputation? Book summary: The Natural Baby Sleep Solution by Polly Moore A day in Antwerp, Belgium Journey of online influencers Two days in Brussels, Belgium Shortcuts - when we love them and when we don't A visit to Rakhigarhi Three days in overhyped Paris Empty Japan, crowded Tokyo The real lock-in in GitHub is not the code, but the stars 11-day Norwegian Breakaway East Caribbean cruise Sanskrit and Sri Lankan Air Force Use REST with Open API The Achilles heel of American capitalism Costa Rica in 4 days At a juice stall in Sri Lanka A short stay at Warsaw, Poland Best practices for using Python & uv inside Docker Two days in Vilnius, Lithuania How IntelliJ IDEs waste disk space Pregnancy Why there aren't many digital nomads from India Two days in Riga, Latvia To keep your machine secure, run third-party tools inside Docker
Infinite network timeouts in Java and Go
Ashish Bhatia · 2022-06-13 · via ashishb.net

Java made a huge mistake of having no network timeouts. A network request can block a thread forever. Even Python did the same. The language designers should have chosen some conservative appropriate numbers instead.

What’s surprising is that the Go language repeated it! Here’s a simple demo

Let’s first create a server that would block forever

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Usage: go run server.go
package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func main() {
    startWebServer(8080)
}

func startWebServer(port int) {
    http.HandleFunc("/block-forever", blockForeverHandler)
    log.Printf("Serving on port %d", port)
    log.Fatal("%s", http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}

func blockForeverHandler(w http.ResponseWriter, req *http.Request) {
    // Do nothing and block forever
    count := 0
    for true {
        time.Sleep(1 * time.Second)
        count++
        log.Printf("Blocked since %d seconds ago...", count)
    }
}

Start the server in one shell with `go run server.go`, you can test it out by visiting http://localhost:8080/block-forever or by doing `curl http://localhost:8080/block-forever` in the shell.

Now, connect to that server in another shell with the following code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Usage: go run client.go
package main

import (
    "log"
    "net/http"
)

func main() {
    fetchData("http://localhost:8080/block-forever")
}

func fetchData(urlStr string) {
    log.Printf("Fetching data from %s", urlStr)
    _, err := http.Get(urlStr)
    if err != nil {
        log.Fatalln(err)
    }
    log.Printf("Received data from %s", urlStr)
}

And wait for it complete, it won’t.

So what’s the fix? Add a timeout before making the request

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Usage: go run client.go
package main

import (
    "log"
    "net/http"
    "time"
)

func main() {
    fetchDataWithTimeout("http://localhost:8080/block-forever")
}

func fetchDataWithTimeout(urlStr string) {
    log.Printf("Fetching data from %s", urlStr)
    client := &http.Client{
        Timeout: 15 * time.Second,
    }
    _, err := client.Get(urlStr)
    if err != nil {
        log.Fatalln(err)
    }
    log.Printf("Received data from %s", urlStr)
}

This will demonstrate the correct behavior by failing with

1
2
3
Fetching data from http://localhost:8080/block-forever
Get "http://localhost:8080/block-forever": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
exit status 1