github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2015/go-for-java-programmers.slide (about) 1 Go for Java Programmers 2 3 Sameer Ajmani 4 Tech Lead Manager, Go team 5 Google 6 @Sajma 7 sameer@golang.org 8 9 * Video 10 11 This talk was presented at [[http://javasig.com][NYJavaSIG]] on April 23, 2015. 12 13 .link https://www.youtube.com/watch?v=_c_tQ6_3cCg Watch the talk on YouTube 14 15 * Outline 16 17 1. What is Go, and who uses it? 18 2. Comparing Go and Java 19 3. Examples 20 4. Concurrency 21 5. Tools 22 23 # The next several slides are from rsc's 2013/distsys and 2015/mit talks. 24 25 * What is Go? 26 27 "Go is an open source programming language that makes it easy to build simple, reliable, and efficient software." 28 29 .link http://golang.org 30 31 * History 32 33 Design began in late 2007. 34 35 - Robert Griesemer, Rob Pike, and Ken Thompson. 36 - Ian Lance Taylor and Russ Cox. 37 38 Open source since 2009 with a very active community. 39 40 Language stable as of Go 1, early 2012. 41 42 * Why Go? 43 44 Go is an answer to problems of scale at Google. 45 46 .image ../2012/splash/datacenter.jpg 500 _ 47 48 * System Scale 49 50 - designed to scale to 10⁶⁺ machines 51 - everyday jobs run on 1000s of machines 52 - jobs coordinate, interact with others in the system 53 - lots going on at once 54 55 Solution: great support for concurrency 56 57 .image ../2012/waza/gophercomplex6.jpg 58 59 * A Second Problem: Engineering Scale 60 61 In 2011: 62 63 - 5000+ developers across 40+ offices 64 - 20+ changes per minute 65 - 50% of code base changes every month 66 - 50 million test cases executed per day 67 - single code tree 68 69 Solution: design the language for large code bases 70 71 * Who uses Go at Google? 72 73 Lots of projects. Thousands of Go programmers. Millions of lines of Go code. 74 75 Public examples: 76 77 - SPDY proxy for Chrome on mobile devices 78 79 .image go-for-java-programmers/spdy.png 400 _ 80 81 * Who uses Go at Google? 82 83 Lots of projects. Thousands of Go programmers. Millions of lines of Go code. 84 85 Public examples: 86 87 - SPDY proxy for Chrome on mobile devices 88 - Download server for Chrome, ChromeOS, Android SDK, Earth, etc. 89 - YouTube Vitess MySQL balancer 90 91 The target is networked servers, but it's a great general-purpose language. 92 93 * Who uses Go besides Google? 94 95 .link http://golang.org/wiki/GoUsers 96 97 Apcera, Bitbucket, bitly, Canonical, CloudFlare, Core OS, Digital Ocean, Docker, Dropbox, Facebook, Getty Images, GitHub, Heroku, Iron.io, Kubernetes, Medium, MongoDB services, Mozilla services, New York Times, pool.ntp.org, Secret, SmugMug, SoundCloud, Stripe, Square, Thomson Reuters, Tumblr, ... 98 99 .image ../2014/state-of-go/bus.jpg 300 _ 100 101 * Comparing Go and Java 102 103 * Go and Java have much in common 104 105 - C family (imperative, braces) 106 - Statically typed 107 - Garbage collected 108 - Memory safe (nil references, runtime bounds checks) 109 - Variables are always initialized (zero/nil/false) 110 - Methods 111 - Interfaces 112 - Type assertions (`instanceof`) 113 - Reflection 114 115 * Go differs from Java in several ways 116 117 - Programs compile to machine code. There's no VM. 118 - Statically linked binaries 119 - Control over memory layout 120 - Function values and lexical closures 121 - Built-in strings (UTF-8) 122 - Built-in generic maps and arrays/slices 123 - Built-in concurrency 124 125 * Go intentionally leaves out many features 126 127 - No classes 128 - No constructors 129 - No inheritance 130 - No `final` 131 - No exceptions 132 - No annotations 133 - No user-defined generics 134 135 * Why does Go leave out those features? 136 137 Clarity is critical. 138 139 When reading code, it should be clear what the program will do. 140 141 When writing code, it should be clear how to make the program do what you want. 142 143 Sometimes this means writing out a loop instead of invoking an obscure function. 144 145 (Don't DRY out.) 146 147 For more background on design: 148 149 - [[http://commandcenter.blogspot.com/2012/06/less-is-exponentially-more.html][Less is exponentially more (Pike, 2012)]] 150 - [[http://talks.golang.org/2012/splash.article][Go at Google: Language Design in the Service of Software Engineering (Pike, 2012)]] 151 152 * Examples 153 154 * Go looks familiar to Java programmers 155 156 Main.java 157 158 .code go-for-java-programmers/hello/Main.java 159 160 hello.go 161 162 .play go-for-java-programmers/hello/hello.go 163 164 * Hello, web server 165 166 .play go-for-java-programmers/hello/server.go 167 168 Types follow names in declarations. 169 Exported names are Capitalized. Unexported names are not. 170 171 * Example: Google Search frontend 172 173 .image go-for-java-programmers/frontend-screenshot.png _ 1000 174 175 .play go-for-java-programmers/frontend.go /func main/,/func handleSearch/ 176 177 * Validate the query 178 179 .code go-for-java-programmers/frontend.go /func handleSearch/,/ENDQUERY/ 180 181 `FormValue` is a method on the type `*http.Request`: 182 183 package http 184 type Request struct {...} 185 func (r *Request) FormValue(key string) string {...} 186 187 `query`:=`req.FormValue("q")` initializes a new variable `query` with 188 the type of the expression on the right hand side, `string`. 189 190 * Fetch the search results 191 192 .code go-for-java-programmers/frontend.go /Run the Google search/,/ENDSEARCH/ 193 194 `Search` returns two values, a slice of results and an error. 195 196 func Search(query string) ([]Result, error) {...} 197 198 The results are valid only if the error is nil. 199 200 type error interface { 201 Error() string // a useful human-readable error message 202 } 203 204 Errors may contain additional information, accessed via type assertions. 205 206 * Render the search results 207 208 .code go-for-java-programmers/frontend.go /Render the/,/ENDRENDER/ 209 210 `resultsTemplate.Execute` generates HTML and writes it to an `io.Writer`: 211 212 type Writer interface { 213 Write(p []byte) (n int, err error) 214 } 215 216 `http.ResponseWriter` implements the `io.Writer` interface. 217 218 * HTML templates operate on Go values 219 220 .play go-for-java-programmers/frontend.go /A Result contains/,/\)\)/ 221 222 * Issue the query to the Google Search API 223 224 .code go-for-java-programmers/frontend.go /func Search/,/resp.Body.Close/ 225 226 The `defer` statement arranges for `resp.Body.Close` to run when `Search` returns. 227 228 * Parse the JSON response into a Go struct 229 230 .link https://developers.google.com/web-search/docs/#fonje 231 232 .code go-for-java-programmers/frontend.go /var jsonResponse/,/^}/ 233 234 * That's it for the frontend 235 236 All the packages are from the standard library: 237 238 import ( 239 "encoding/json" 240 "fmt" 241 "html/template" 242 "log" 243 "net/http" 244 "net/url" 245 "time" 246 ) 247 248 Go servers scale well: each request runs in its own _goroutine_. 249 250 Let's talk about concurrency. 251 252 * Communicating Sequential Processes (Hoare, 1978) 253 254 Concurrent programs are structured as independent processes that 255 execute sequentially and communicate by passing messages. 256 257 Sequential execution is easy to understand. Async callbacks are not. 258 259 "Don't communicate by sharing memory, share memory by communicating." 260 261 *Go*primitives:* goroutines, channels, and the `select` statement. 262 263 * Goroutines 264 265 Goroutines are like lightweight threads. 266 267 They start with tiny stacks and resize as needed. 268 269 Go programs can have hundreds of thousands of them. 270 271 Start a goroutine using the `go` statement: 272 273 go f(args) 274 275 The Go runtime schedules goroutines onto OS threads. 276 277 Blocked goroutines don't use a thread. 278 279 * Channels 280 281 Channels provide communication between goroutines. 282 283 c := make(chan string) 284 285 // goroutine 1 286 c <- "hello!" 287 288 // goroutine 2 289 s := <-c 290 fmt.Println(s) // "hello!" 291 292 * Select 293 294 A `select` statement blocks until communication can proceed. 295 296 select { 297 case n := <-in: 298 fmt.Println("received", n) 299 case out <- v: 300 fmt.Println("sent", v) 301 } 302 303 Only the selected case runs. 304 305 * Example: Google Search (backend) 306 307 Q: What does Google search do? 308 309 A: Given a query, return a page of search results (and some ads). 310 311 Q: How do we get the search results? 312 313 A: Send the query to Web search, Image search, YouTube, Maps, News, etc., then mix the results. 314 315 How do we implement this? 316 317 * Google Search: A fake framework 318 319 We can simulate a Search function with a random timeout up to 100ms. 320 321 .code go-for-java-programmers/google-serial.go /START2/,/STOP2/ 322 323 * Google Search: Test the framework 324 325 .play go-for-java-programmers/google-serial.go /func.main/,/}/ 326 327 * Google Search (serial) 328 329 The Google function takes a query and returns a slice of Results (which are just strings). 330 331 Google invokes Web, Image, and Video searches serially, appending them to the results slice. 332 333 .play go-for-java-programmers/google-serial.go /START1/,/STOP1/ 334 335 * Google Search (parallel) 336 337 Run the Web, Image, and Video searches concurrently, and wait for all results. 338 339 The `func` literals are closures over `query` and `c`. 340 341 .play go-for-java-programmers/google-parallel.go /Google/,/^}/ 342 343 * Google Search (timeout) 344 345 Don't wait for slow servers. 346 347 No locks. No condition variables. No callbacks. 348 349 .play go-for-java-programmers/google-timeout.go /START/,/STOP/ 350 351 * Avoid timeout 352 353 Q: How do we avoid discarding results from slow servers? 354 355 A: Replicate the servers. Send requests to multiple replicas, and use the first response. 356 357 .code go-for-java-programmers/first.go /START1/,/STOP1/ 358 359 * Using the First function 360 361 .play go-for-java-programmers/first.go /START2/,/STOP2/ 362 363 * Google Search (replicated) 364 365 Reduce tail latency using replicated search servers. 366 367 .play go-for-java-programmers/google-first.go /START/,/STOP/ 368 369 * And still… 370 371 No locks. No condition variables. No callbacks. 372 373 * Summary 374 375 In just a few simple transformations we used Go's concurrency primitives to convert a 376 377 - slow 378 - sequential 379 - failure-sensitive 380 381 program into one that is 382 383 - fast 384 - concurrent 385 - replicated 386 - robust. 387 388 * Tools 389 390 * Go has great tools 391 392 - gofmt and goimports 393 - the go tool 394 - godoc 395 - IDE and editor support 396 397 The language is designed for tooling. 398 399 * gofmt and goimports 400 401 Gofmt formats code automatically. No options. 402 403 Goimports updates import statements based on your workspace. 404 405 Most people run these tools on save. 406 407 .link http://play.golang.org/p/GPqra77cBK 408 409 * The go tool 410 411 The go tool builds Go programs from source in a conventional directory layout. 412 No Makefiles or other configs. 413 414 Fetch the `present` tool and its dependencies, build it, and install it: 415 416 % go get golang.org/x/tools/cmd/present 417 418 Run it: 419 420 % present 421 422 * godoc 423 424 Generated documentation for the world's open-source Go code: 425 426 .link http://godoc.org 427 428 * IDE and editor support 429 430 Eclipse, IntelliJ, emacs, vim, many others. 431 432 - `gofmt` 433 - `goimports` 434 - `godoc` lookups 435 - code completion 436 - code navigation 437 438 There's no "Go IDE". 439 440 Go tools meet you where you are. 441 442 * Where to Go next 443 444 Take the Go Tour online. 445 446 .link http://tour.golang.org 447 448 Lots more material. 449 450 .link http://golang.org/wiki/Learn 451 452 Great community. 453 454 .link http://golang.org/project