Golang quiz
any variable
any 有 static type 跟 dynamic type
猜猜以下的結果
atomic int
使用 atomic package 運算,有 Int64 & Int32 沒有 Int,
其中注意到有 atomic.Value 看起來很方便,從 Example 看到可以更新 Config
會有警告
需要使用 ans.Load()
讀值
slice grows policy
https://github.com/golang/go/blob/master/src/runtime/slice.go#L177
小於 256 兩倍
其他的用 (newcap + 3*threshold) >> 2
,當 newcap 很大的時候,相當於 newcap >> 2
也就是 1/4 = 0.25
runtime: make slice growth formula a bit smoother
concurrency in map
原生的 map 是不支援 concurrency 的
會導致 fatal error
而 sync.Map 是 concurrent safe
sync.Map 在以下兩種情況做最佳化
- when the entry for a given key is only ever written once but read many times, as in caches that only grow
- when multiple goroutines read, write, and overwrite entries for disjoint sets of keys.
不過在 GopherCon 2024 有位講者發現在多讀少寫情境下,map + RWMutex 的效能比 sync.Map 好
GC
A Guide to the Go Garbage Collector
Scheduling In Go
Go 使用 GMP model schedule
https://www.ardanlabs.com/blog/2018/08/scheduling-in-go-part1.html
Race Detector
https://go.dev/doc/articles/race_detector
pprof
https://darjun.github.io/2021/06/09/youdontknowgo/pprof/
database & system design
Transaction & ACID
What is Transaction?
Transaction is a sequence of operations that are treated as a single logical unit of work.
- Atomicity: The result of transaction is all or nothing. Meaning that if one fails, the entire transaction fails and is rolled back.
- Consistency: The database remains in a consistent state before and after the transaction.
- Isolation: Transactions are isolated from each other. Intermediate results are not visible to other transactions.
- Durability: Once transaction is committed, the changes are permanent, even in case of a system failure.
Example: Banking system
- debit from Account A
- credit to Account B
If something went wrong during the transaction, e.g. failed to credit to Account B. The result is that the money in Account A lost and Account B didn't receive.
Cache Strategy
https://www.jyt0532.com/2018/09/23/cache-mechanism/
Read
跟 cache 讀,沒讀到從 DB 讀,接著更新 cache
- Inline-cache: Read through
- Look-Aside-cache: Read aside
Write
只寫 cache: Write back
只寫 DB: Write around
都寫:Write through/ allocate on Write
Ref