SlideShare ist ein Scribd-Unternehmen logo
1 von 74
Downloaden Sie, um offline zu lesen
A Recovering
Java Developer Learns to Go
Matt Stine (@mstine)
Cloud Foundry Platform Engineer at Pivotal
matt.stine@gmail.com
http://www.mattstine.com
OFFICE HOURS
Wednesday, 2:30 - 3:10 PM
Expo Hall (Table A)
I am not a Go expert.
I’m just learning to Go.
CF Architecture - January 2013
DEA Pool
Router
Cloud Controller
BOSH Director BOSH Agent
UAA/Login Servers Health Manager
Service Broker Node(s)
Messaging (NATS)
CLI Client
Ruby
Java/Spring
Go
CF Architecture - January 2014
Ruby
Java/Spring
Go
Loggregator
DEA Pool (Diego - Coming soon!)
Router
Cloud Controller
BOSH Director BOSH Agent
UAA/Login Servers Health Manager
Service Broker Node(s)
Messaging (NATS)
CLI Client
–Matt Stine
“Hey, wait! I just got done learning Ruby!”
• Mike Gehard: “Go Within Cloud Foundry”

https://www.youtube.com/watch?v=d5aHr8VGU-8
• Onsi Fakhouri: “Diego: Re-envisioning the Elastic Runtime”

https://www.youtube.com/watch?v=1OkmVTFhfLY
Go in Cloud Foundry
✓ Hello World
✓ Why Go?
✓ Contrasts with Java:
- Features and Idioms
- Packaging / Modularity
- Types / OOP / Interfaces
- Concurrency
Agenda
package main
!
import (
"fmt"
)
!
func main() {
fmt.Println("Hello World")
}
Hello World
All code goes
in a package.
Give access to
exported
stuff from other
packages.
Function definition,
main() is entrypoint.
Call an exported function!
Why Go?
Iron Triangle of Language Design
EfficientCompilation
Ease of Programming
EfficientExecution
Systems
Programming
• 2007-09-21: Go invented at Google by Robert Griesemer, Rob Pike, and
Ken Thompson
• 2009-11-10: Go released as OSS
• 2012-03-28: Go 1.0 is Released
A History Lesson
Software Engineering in the LARGE
http://talks.golang.org/2012/splash.article
“Go is a programming language designed by Google to help solve
Google's problems, and Google has big problems.”
Software Engineering in the LARGE
http://talks.golang.org/2012/splash.article
“Go is a programming language designed by Google to help solve
Google's problems, and Google has big problems.”
✓ Safety and efficiency of a

statically-typed, compiled language
✓ Productivity and feel of a dynamic,

interpreted language
✓ Address modern compute environments:
- Multicore Processors
- Networked Systems
- Massive Computational Clusters
- Web Programming Model
Goals
https://www.flickr.com/photos/slackpics/4289782818
A
Kit
for
Systems
Software
https://www.flickr.com/photos/pmiaki/6657150957
Differences from Java
https://www.flickr.com/photos/yukop/6778321940
• Features and Idioms
• Packaging / Modularity
• Types / OOP / Interfaces
• Concurrency
Contrasts with Java
Features
and
Idioms
https://www.flickr.com/photos/yukop/6778321940
Multiple Return Values
func vals() (int, int) {
return 3, 7
}
!
func main() {
a, b := vals()
fmt.Println(a)
fmt.Println(b)
!
_, c := vals()
fmt.Println(c)
} GBE
Return a pair of values.
I
Ignore
the first
value returned.
Assign to
multiple
variables.
Closures
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
GBE
Closes over this state.
Closures
func main() {
nextInt := intSeq()
!
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
!
newInts := intSeq()
fmt.Println(newInts())
}
GBE
Captures its own value for i.
Increments own value of i.
Captures the value of i again!
And increments it.
Where’s my java.util.List? Slices
s := make([]string, 3)
fmt.Println("emp:", s)
!
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
!
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
GBE
Create an empty slice of strings
(zero-valued).
Set value at index.
Get value at index.
Append function (not mutate in-place!).
Where’s my java.util.List? Slices
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
!
l := s[2:5]
fmt.Println("sl1:", l)
!
l = s[:5]
fmt.Println("sl2:", l)
!
t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)
GBE
Length function.
Copy function.
Slicing function:
index 2 (inclusive)
to index 5 (exclusive).
Slicing function:
index 0 (inclusive)
to index 5 (exclusive).
Slice literals!
Where’s my java.util.Map? Maps
m := make(map[string]int)
!
m["k1"] = 7
m["k2"] = 13
!
fmt.Println("map:", m)
!
v1 := m["k1"]
fmt.Println("v1: ", v1)
!
fmt.Println("len:", len(m))
Create an empty map of string ! int.
Put values.
Get value.
Length function.
GBE
Where’s my java.util.Map? Maps
delete(m, "k2")
fmt.Println("map:", m)
!
_, prs := m["k2"]
fmt.Println("prs:", prs)
!
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
Delete function.
Optional second return indicating “presence.”
Map literals!
GBE
Looping with Range
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
!
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
!
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %sn", k, v)
}
Discard first (index),
sum second (value).
Keep both returns!
With maps, first = key,
second = value.
GBE
We don’t need no stinkin’ exceptions…
func f1(arg int) (int, error) {
if arg == 42 {
return -1, errors.New("can't work with 42")
}
return arg + 3, nil
}
!
func main() {
for _, i := range []int{7, 42} {
if r, e := f1(i); e != nil {
fmt.Println("f1 failed:", e)
} else {
fmt.Println("f1 worked:", r)
}
}
}
Conventional: last return is error.
Makes an error with the provided message.
Return nil if there was no error.
Idiomatic inline
error check.
GBE
(Semi)automatic Resource Management
func createFile(p string) *os.File {
fmt.Println("creating")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
!
}
!
func closeFile(f *os.File) {
fmt.Println("closing")
f.Close()
}
GBE
(Semi)automatic Resource Management
func main() {
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
Run after the function
completes.
GBE
Packaging/Modularity
https://www.flickr.com/photos/yukop/6778321940
TL;DR
COMPLEX
SIMPLE
• Every class in a package
• Import classes explicitly
- import java.util.Map
• Import all classes in a package
- import java.util.*
• Statically import class static members:
- import static java.lang.Math.PI
- import static java.lang.Math.*
Java Packaging
• All types and functions belong to a package.
• Every source file must declare its package.
• Import packages to gain access to exported members.
Go Packaging
• public - any class in same package, or any importing class in a different
package, can see
• default (“package private”) - any class in same package can see
• protected - any class in same package, or any subclass in a different
package, can see
• private - no class other than this can see
• Scope indicated by prefixing name at declaration time.
Java Scoping
• exported - any code in an importing file can see
- exported names start with uppercase letter
- func Copy(src *[]byte, dest *[]byte)
• non-exported - only code in the same package can see
- non-exported names start with _ or lowercase letter
- func copy(src *[]byte, dest *[]byte)
- func _Copy(src *[]byte, dest *[]byte)
Go Scoping
• Conventional correspondence to directory paths (e.g. com.ms.foo
should be at src/com/ms/foo) - tools expect this!
• Package paths do not have to be unique at compile or runtime (first
dependency found/loaded wins!)
• Conventional correspondence to URL of author (e.g. my domain is
www.mattstine.com, so my packages names start with com.mattstine) -
but no actual relationship to source code location!
Java Naming
• Conventional correspondence to directory paths (e.g. github.com/go-martini/
martini should be at src/github.com/go-martini/martini) - tools expect this!
• Package paths MUST BE UNIQUE across a $GOPATH.
• Package names do not have to be unique.
• Referring to imported names must be qualified by package name (e.g. sql.DB not just DB)…
can locally alias (e.g. import dbstuff “database/sql”)
• Conventional correspondence to URL of code location (e.g. import http://github.com/
joefitzgerald/cfenv as import “github.com/joefitzgerald/cfenv").
• Can “go get” remote packages - supports Git, SVN, Mercurial, Bazaar.
Go Naming
• Java admits:
- circular package dependencies
- dead imports
• Go rejects:
- circular package dependencies
- dead imports
Miscellany
Types/OOP/Interfaces
https://www.flickr.com/photos/yukop/6778321940
For realz this time…
structs FTW
type Point struct {
X, Y float64
}
Define a type.
Give it a name.
This type is a struct.
(you can actually define others!)
Add stuff!
(upcase exports apply here too!)
Methods are Functions!
func (p Point) Translate(xDist float64, yDist float64) Point {
return Point{p.X + xDist, p.Y + yDist}
}
Receiver argument!
Can define methods on pointers or values.
composition FTW
type Point struct {
X, Y float64
}
!
const (
BLUE = iota
RED = iota
GREEN = iota
)
!
type ColorPoint struct {
Point Point
Color int
}
Define an enumerated constant
(closest to Java enum).
A ColorPoint has-a Point!
• I have Points.
• I have ColorPoints.
• ColorPoints are like Points, but they are not Points.
• But I want to compute the euclidean distance between them.
• What to do?
Problem
Interfaces Group Behaviors
type Positioner interface {
Coordinates() Point
}
!
type Distancer interface {
DistanceTo(p Positioner) float64
}
It’s all about satisfaction…
Java = explicit
!
Go = implicit
Calculating Distance
func distanceBetween(a Positioner, b Positioner)
float64 {
p := a.Coordinates()
q := b.Coordinates()
sqOfXDist := math.Pow(p.X-q.X, 2)
sqOfYDist := math.Pow(p.Y-q.Y, 2)
return math.Sqrt(sqOfXDist + sqOfYDist)
}
Point Satisfies Distancer and Positioner
func (p Point) Coordinates() Point {
return p
}
!
func (p Point) DistanceTo(pos Positioner) float64
{
return distanceBetween(p, pos)
}
ColorPoint Satisfies Distancer and Positioner
func (cp ColorPoint) Coordinates() Point {
return cp.Point
}
!
func (cp ColorPoint) DistanceTo(pos Positioner)
float64 {
return distanceBetween(cp, pos)
}
Behavior Not Taxonomy
Animal Satisfies Distancer and Positioner
func (a Animal) Coordinates() point.Point {
return point.Point{X: a.X, Y: a.Y}
}
!
func (a Animal) DistanceTo(pos point.Positioner)
float64 {
thing := pos.Coordinates()
sqOfXDist := math.Pow(a.X-thing.X, 2)
sqOfYDist := math.Pow(a.Y-thing.Y, 2)
return math.Sqrt(sqOfXDist + sqOfYDist)
}
Go!
p = point.Point{X: 1, Y: 2}
q := point.ColorPoint{Point: point.Point{X: 1, Y: 4},
Color: point.BLUE}
!
fmt.Printf("Dist b/w p and q = %vn", p.DistanceTo(q))
fmt.Printf("Dist b/w q and p = %vn", q.DistanceTo(p))
!
penguin := animal.Animal{Name: "penguin", X: 1, Y: 1}
seal := animal.Animal{Name: "seal", X: 1, Y: 4}
!
fmt.Printf("Dist b/w penguin and seal = %vn",
penguin.DistanceTo(seal))
fmt.Printf("Dist b/w penguin and point = %vn",
penguin.DistanceTo(p))
Concurrency
https://www.flickr.com/photos/yukop/6778321940
• Parallelism = leveraging simultaneous execution of work to perform
many things at once. Limited to number of processors/cores you have.
• Concurrency = composition of work to manage many things at once. No
theoretical limit.
• Rob Pike: “Concurrency is Not Parallelism”

http://www.youtube.com/watch?v=cN_DpYBzKso
Concurrency vs Parallelism
• Java
- Threads
- OS managed
- Share address space with other threads in same process
• Go
- Goroutines
- user-space managed by language runtime
- multiplexed onto pool of OS threads
Parallelism - How?
• Java
- Shared memory
- Locking
• Go
- Can share memory (see http://golang.org/pkg/sync)
- But there is a better way!
Synchronization?
– http://golang.org/doc/effective_go.html
“Do not communicate by sharing memory; instead,
share memory by communicating.”
Goroutines
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
!
func main() {
f("direct")
!
go f("goroutine")
!
go func(msg string) {
fmt.Println(msg)
}("going")
} GBE
Synchronous
Asynchronous
Asynchronous
and Anonymous
Channels
func main() {
messages := make(chan string)
!
go func() { messages <- "ping" }()
!
msg := <-messages
fmt.Println(msg)
}
GBE
Create a new channel.
Sending
Receiving
Channel Buffering
func main() {
messages := make(chan string, 2)
!
messages <- "buffered"
messages <- "channel"
!
fmt.Println(<-messages)
fmt.Println(<-messages)
}
GBE
Make a channel that will
buffer two values.
Send twice
Receive twice
Channel Synchronization
func worker(done chan bool) {
fmt.Print("working...")
time.Sleep(time.Second)
fmt.Println("done")
done <- true
}
!
func main() {
done := make(chan bool, 1)
go worker(done)
<-done
} GBE
Notify receive that I’m done.
Run worker on a
goroutine, pass “done”
channel.
Block until msg
received!
Select
c1 := make(chan string)
c2 := make(chan string)
!
go func() {
time.Sleep(time.Second * 1)
c1 <- "one"
}()
go func() {
time.Sleep(time.Second * 2)
c2 <- "two"
}()
GBE
Create two channels.
Create two goroutines; each
sends message to different channel.
Select
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
GBE
Await both messages
simultaneously!
Print each as it arrives!
Closing Channels
jobs := make(chan int, 5)
done := make(chan bool)
!
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
GBE
Job channel for sending work.
Done channel to indicate
all work complete.
Receive jobs - more will be
false if jobs is closed.
If no more jobs, say that I’m done!
Closing Channels
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
!
<-done
GBE
Send the jobs to the worker.
Close the jobs channel.
Block until the worker is finished.
Range Over Channels
func main() {
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
!
for elem := range queue {
fmt.Println(elem)
}
}
GBE
Pull messages off channel
for each iteration of the loop.
• Features and Idioms
• Packaging / Modularity
• Types / OOP / Interfaces
• Concurrency
Contrasts with Java
Thank You!!!
Matt Stine (@mstine)
Cloud Foundry Platform Engineer at Pivotal
matt.stine@gmail.com
http://www.mattstine.com
OFFICE HOURS
Wednesday, 2:30 - 3:10 PM
Expo Hall (Table A)
Code samples marked “GBE” at https://gobyexample.com are by Mark McGranaghan and are Creative Commons Attribution 3.0
Unported licensed (http://creativecommons.org/licenses/by/3.0).
!
The Go Gopher logo was created by Renee French and is Creative Commons Attribution 3.0 Unported licensed (http://
creativecommons.org/licenses/by/3.0).
!
The Java Duke logo is BSD licensed (http://opensource.org/licenses/bsd-license.php).

Weitere ähnliche Inhalte

Was ist angesagt?

7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)Steven Francia
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersDiego Freniche Brito
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersKostas Saidis
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails introMiguel Pastor
 
A Plan towards Ruby 3 Types
A Plan towards Ruby 3 TypesA Plan towards Ruby 3 Types
A Plan towards Ruby 3 Typesmametter
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum
 
JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?Leonardo Zanivan
 
DaNode - A home made web server in D
DaNode - A home made web server in DDaNode - A home made web server in D
DaNode - A home made web server in DAndrei Alexandrescu
 
Ruby projects of interest for DevOps
Ruby projects of interest for DevOpsRuby projects of interest for DevOps
Ruby projects of interest for DevOpsRicardo Sanchez
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
Running a Plone product on Substance D
Running a Plone product on Substance DRunning a Plone product on Substance D
Running a Plone product on Substance DMakina Corpus
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemKostas Saidis
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!Iván López Martín
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
Transmogrifier: content migration and time traveling
Transmogrifier: content migration and time travelingTransmogrifier: content migration and time traveling
Transmogrifier: content migration and time travelingJoão Bueno
 

Was ist angesagt? (20)

7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
 
A Plan towards Ruby 3 Types
A Plan towards Ruby 3 TypesA Plan towards Ruby 3 Types
A Plan towards Ruby 3 Types
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?
 
DaNode - A home made web server in D
DaNode - A home made web server in DDaNode - A home made web server in D
DaNode - A home made web server in D
 
Ruby projects of interest for DevOps
Ruby projects of interest for DevOpsRuby projects of interest for DevOps
Ruby projects of interest for DevOps
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Rust 101 (2017 edition)
Rust 101 (2017 edition)Rust 101 (2017 edition)
Rust 101 (2017 edition)
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
Running a Plone product on Substance D
Running a Plone product on Substance DRunning a Plone product on Substance D
Running a Plone product on Substance D
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!JavaCro 2016 - From Java to Groovy: Adventure Time!
JavaCro 2016 - From Java to Groovy: Adventure Time!
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Transmogrifier: content migration and time traveling
Transmogrifier: content migration and time travelingTransmogrifier: content migration and time traveling
Transmogrifier: content migration and time traveling
 

Andere mochten auch

Beyond Java: Go for Java developers
Beyond Java: Go for Java developersBeyond Java: Go for Java developers
Beyond Java: Go for Java developersNetcetera
 
Boldly go where the Java programming language has never gone before
Boldly go where the Java programming language has never gone beforeBoldly go where the Java programming language has never gone before
Boldly go where the Java programming language has never gone beforeelliando dias
 
The Go features I can't live without
The Go features I can't live withoutThe Go features I can't live without
The Go features I can't live withoutRodolfo Carvalho
 
Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Steven Francia
 
Golang server design pattern
Golang server design patternGolang server design pattern
Golang server design pattern理 傅
 
HTTP/2 and Java: Current Status
HTTP/2 and Java: Current StatusHTTP/2 and Java: Current Status
HTTP/2 and Java: Current StatusSimone Bordet
 

Andere mochten auch (9)

Beyond Java: Go for Java developers
Beyond Java: Go for Java developersBeyond Java: Go for Java developers
Beyond Java: Go for Java developers
 
Boldly go where the Java programming language has never gone before
Boldly go where the Java programming language has never gone beforeBoldly go where the Java programming language has never gone before
Boldly go where the Java programming language has never gone before
 
The Go features I can't live without
The Go features I can't live withoutThe Go features I can't live without
The Go features I can't live without
 
Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go
 
Golang server design pattern
Golang server design patternGolang server design pattern
Golang server design pattern
 
Golang for OO Programmers
Golang for OO ProgrammersGolang for OO Programmers
Golang for OO Programmers
 
Practical Look at Erlang
Practical Look at ErlangPractical Look at Erlang
Practical Look at Erlang
 
HTTP/2 and Java: Current Status
HTTP/2 and Java: Current StatusHTTP/2 and Java: Current Status
HTTP/2 and Java: Current Status
 
HTTP/2 Comes to Java
HTTP/2 Comes to JavaHTTP/2 Comes to Java
HTTP/2 Comes to Java
 

Ähnlich wie A Recovering Java Developer Learns to Go

Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 

Ähnlich wie A Recovering Java Developer Learns to Go (20)

Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Os Secoske
Os SecoskeOs Secoske
Os Secoske
 
Groovy
GroovyGroovy
Groovy
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Twig Templating
Twig TemplatingTwig Templating
Twig Templating
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 

Mehr von Matt Stine

Architectures That Bend but Don't Break
Architectures That Bend but Don't BreakArchitectures That Bend but Don't Break
Architectures That Bend but Don't BreakMatt Stine
 
Cloud Native Architecture Patterns Tutorial
Cloud Native Architecture Patterns TutorialCloud Native Architecture Patterns Tutorial
Cloud Native Architecture Patterns TutorialMatt Stine
 
Resilient Architecture
Resilient ArchitectureResilient Architecture
Resilient ArchitectureMatt Stine
 
Cloud Foundry: The Best Place to Run Microservices
Cloud Foundry: The Best Place to Run MicroservicesCloud Foundry: The Best Place to Run Microservices
Cloud Foundry: The Best Place to Run MicroservicesMatt Stine
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaMatt Stine
 
Lattice: A Cloud-Native Platform for Your Spring Applications
Lattice: A Cloud-Native Platform for Your Spring ApplicationsLattice: A Cloud-Native Platform for Your Spring Applications
Lattice: A Cloud-Native Platform for Your Spring ApplicationsMatt Stine
 
The Cloud Native Journey
The Cloud Native JourneyThe Cloud Native Journey
The Cloud Native JourneyMatt Stine
 
To Microservices and Beyond
To Microservices and BeyondTo Microservices and Beyond
To Microservices and BeyondMatt Stine
 
Deploying Microservices to Cloud Foundry
Deploying Microservices to Cloud FoundryDeploying Microservices to Cloud Foundry
Deploying Microservices to Cloud FoundryMatt Stine
 
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
Cloud Foundry Diego: Modular and Extensible Substructure for MicroservicesCloud Foundry Diego: Modular and Extensible Substructure for Microservices
Cloud Foundry Diego: Modular and Extensible Substructure for MicroservicesMatt Stine
 
Building Distributed Systems with Netflix OSS and Spring Cloud
Building Distributed Systems with Netflix OSS and Spring CloudBuilding Distributed Systems with Netflix OSS and Spring Cloud
Building Distributed Systems with Netflix OSS and Spring CloudMatt Stine
 
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web ServicesPivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web ServicesMatt Stine
 
Agile Development with OSGi
Agile Development with OSGiAgile Development with OSGi
Agile Development with OSGiMatt Stine
 
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
Cloud Foundry and Microservices: A Mutualistic Symbiotic RelationshipCloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
Cloud Foundry and Microservices: A Mutualistic Symbiotic RelationshipMatt Stine
 
It's the End of the Cloud as We Know It
It's the End of the Cloud as We Know ItIt's the End of the Cloud as We Know It
It's the End of the Cloud as We Know ItMatt Stine
 
Functional solid
Functional solidFunctional solid
Functional solidMatt Stine
 
The Seven Wastes of Software Development
The Seven Wastes of Software DevelopmentThe Seven Wastes of Software Development
The Seven Wastes of Software DevelopmentMatt Stine
 
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Information Sciences Solutions to Core Facility Problems at St. Jude Children...Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Information Sciences Solutions to Core Facility Problems at St. Jude Children...Matt Stine
 
Achieve Your Goals
Achieve Your GoalsAchieve Your Goals
Achieve Your GoalsMatt Stine
 

Mehr von Matt Stine (20)

Architectures That Bend but Don't Break
Architectures That Bend but Don't BreakArchitectures That Bend but Don't Break
Architectures That Bend but Don't Break
 
Cloud Native Architecture Patterns Tutorial
Cloud Native Architecture Patterns TutorialCloud Native Architecture Patterns Tutorial
Cloud Native Architecture Patterns Tutorial
 
Resilient Architecture
Resilient ArchitectureResilient Architecture
Resilient Architecture
 
Cloud Foundry: The Best Place to Run Microservices
Cloud Foundry: The Best Place to Run MicroservicesCloud Foundry: The Best Place to Run Microservices
Cloud Foundry: The Best Place to Run Microservices
 
Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
 
Lattice: A Cloud-Native Platform for Your Spring Applications
Lattice: A Cloud-Native Platform for Your Spring ApplicationsLattice: A Cloud-Native Platform for Your Spring Applications
Lattice: A Cloud-Native Platform for Your Spring Applications
 
The Cloud Native Journey
The Cloud Native JourneyThe Cloud Native Journey
The Cloud Native Journey
 
To Microservices and Beyond
To Microservices and BeyondTo Microservices and Beyond
To Microservices and Beyond
 
Deploying Microservices to Cloud Foundry
Deploying Microservices to Cloud FoundryDeploying Microservices to Cloud Foundry
Deploying Microservices to Cloud Foundry
 
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
Cloud Foundry Diego: Modular and Extensible Substructure for MicroservicesCloud Foundry Diego: Modular and Extensible Substructure for Microservices
Cloud Foundry Diego: Modular and Extensible Substructure for Microservices
 
Building Distributed Systems with Netflix OSS and Spring Cloud
Building Distributed Systems with Netflix OSS and Spring CloudBuilding Distributed Systems with Netflix OSS and Spring Cloud
Building Distributed Systems with Netflix OSS and Spring Cloud
 
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web ServicesPivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
Pivotal Cloud Platform Roadshow: Sign Up for Pivotal Web Services
 
Agile Development with OSGi
Agile Development with OSGiAgile Development with OSGi
Agile Development with OSGi
 
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
Cloud Foundry and Microservices: A Mutualistic Symbiotic RelationshipCloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
Cloud Foundry and Microservices: A Mutualistic Symbiotic Relationship
 
It's the End of the Cloud as We Know It
It's the End of the Cloud as We Know ItIt's the End of the Cloud as We Know It
It's the End of the Cloud as We Know It
 
Vert.x
Vert.xVert.x
Vert.x
 
Functional solid
Functional solidFunctional solid
Functional solid
 
The Seven Wastes of Software Development
The Seven Wastes of Software DevelopmentThe Seven Wastes of Software Development
The Seven Wastes of Software Development
 
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Information Sciences Solutions to Core Facility Problems at St. Jude Children...Information Sciences Solutions to Core Facility Problems at St. Jude Children...
Information Sciences Solutions to Core Facility Problems at St. Jude Children...
 
Achieve Your Goals
Achieve Your GoalsAchieve Your Goals
Achieve Your Goals
 

A Recovering Java Developer Learns to Go

  • 1. A Recovering Java Developer Learns to Go Matt Stine (@mstine) Cloud Foundry Platform Engineer at Pivotal matt.stine@gmail.com http://www.mattstine.com OFFICE HOURS Wednesday, 2:30 - 3:10 PM Expo Hall (Table A)
  • 2. I am not a Go expert.
  • 4. CF Architecture - January 2013 DEA Pool Router Cloud Controller BOSH Director BOSH Agent UAA/Login Servers Health Manager Service Broker Node(s) Messaging (NATS) CLI Client Ruby Java/Spring Go
  • 5. CF Architecture - January 2014 Ruby Java/Spring Go Loggregator DEA Pool (Diego - Coming soon!) Router Cloud Controller BOSH Director BOSH Agent UAA/Login Servers Health Manager Service Broker Node(s) Messaging (NATS) CLI Client
  • 6. –Matt Stine “Hey, wait! I just got done learning Ruby!”
  • 7. • Mike Gehard: “Go Within Cloud Foundry”
 https://www.youtube.com/watch?v=d5aHr8VGU-8 • Onsi Fakhouri: “Diego: Re-envisioning the Elastic Runtime”
 https://www.youtube.com/watch?v=1OkmVTFhfLY Go in Cloud Foundry
  • 8. ✓ Hello World ✓ Why Go? ✓ Contrasts with Java: - Features and Idioms - Packaging / Modularity - Types / OOP / Interfaces - Concurrency Agenda
  • 9. package main ! import ( "fmt" ) ! func main() { fmt.Println("Hello World") } Hello World All code goes in a package. Give access to exported stuff from other packages. Function definition, main() is entrypoint. Call an exported function!
  • 11. Iron Triangle of Language Design EfficientCompilation Ease of Programming EfficientExecution Systems Programming
  • 12. • 2007-09-21: Go invented at Google by Robert Griesemer, Rob Pike, and Ken Thompson • 2009-11-10: Go released as OSS • 2012-03-28: Go 1.0 is Released A History Lesson
  • 13. Software Engineering in the LARGE http://talks.golang.org/2012/splash.article “Go is a programming language designed by Google to help solve Google's problems, and Google has big problems.”
  • 14. Software Engineering in the LARGE http://talks.golang.org/2012/splash.article “Go is a programming language designed by Google to help solve Google's problems, and Google has big problems.”
  • 15. ✓ Safety and efficiency of a
 statically-typed, compiled language ✓ Productivity and feel of a dynamic,
 interpreted language ✓ Address modern compute environments: - Multicore Processors - Networked Systems - Massive Computational Clusters - Web Programming Model Goals
  • 19. • Features and Idioms • Packaging / Modularity • Types / OOP / Interfaces • Concurrency Contrasts with Java
  • 21. Multiple Return Values func vals() (int, int) { return 3, 7 } ! func main() { a, b := vals() fmt.Println(a) fmt.Println(b) ! _, c := vals() fmt.Println(c) } GBE Return a pair of values. I Ignore the first value returned. Assign to multiple variables.
  • 22. Closures func intSeq() func() int { i := 0 return func() int { i += 1 return i } } GBE Closes over this state.
  • 23. Closures func main() { nextInt := intSeq() ! fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) ! newInts := intSeq() fmt.Println(newInts()) } GBE Captures its own value for i. Increments own value of i. Captures the value of i again! And increments it.
  • 24. Where’s my java.util.List? Slices s := make([]string, 3) fmt.Println("emp:", s) ! s[0] = "a" s[1] = "b" s[2] = "c" fmt.Println("set:", s) fmt.Println("get:", s[2]) ! s = append(s, "d") s = append(s, "e", "f") fmt.Println("apd:", s) GBE Create an empty slice of strings (zero-valued). Set value at index. Get value at index. Append function (not mutate in-place!).
  • 25. Where’s my java.util.List? Slices c := make([]string, len(s)) copy(c, s) fmt.Println("cpy:", c) ! l := s[2:5] fmt.Println("sl1:", l) ! l = s[:5] fmt.Println("sl2:", l) ! t := []string{"g", "h", "i"} fmt.Println("dcl:", t) GBE Length function. Copy function. Slicing function: index 2 (inclusive) to index 5 (exclusive). Slicing function: index 0 (inclusive) to index 5 (exclusive). Slice literals!
  • 26. Where’s my java.util.Map? Maps m := make(map[string]int) ! m["k1"] = 7 m["k2"] = 13 ! fmt.Println("map:", m) ! v1 := m["k1"] fmt.Println("v1: ", v1) ! fmt.Println("len:", len(m)) Create an empty map of string ! int. Put values. Get value. Length function. GBE
  • 27. Where’s my java.util.Map? Maps delete(m, "k2") fmt.Println("map:", m) ! _, prs := m["k2"] fmt.Println("prs:", prs) ! n := map[string]int{"foo": 1, "bar": 2} fmt.Println("map:", n) Delete function. Optional second return indicating “presence.” Map literals! GBE
  • 28. Looping with Range nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:", sum) ! for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } ! kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %sn", k, v) } Discard first (index), sum second (value). Keep both returns! With maps, first = key, second = value. GBE
  • 29. We don’t need no stinkin’ exceptions… func f1(arg int) (int, error) { if arg == 42 { return -1, errors.New("can't work with 42") } return arg + 3, nil } ! func main() { for _, i := range []int{7, 42} { if r, e := f1(i); e != nil { fmt.Println("f1 failed:", e) } else { fmt.Println("f1 worked:", r) } } } Conventional: last return is error. Makes an error with the provided message. Return nil if there was no error. Idiomatic inline error check. GBE
  • 30. (Semi)automatic Resource Management func createFile(p string) *os.File { fmt.Println("creating") f, err := os.Create(p) if err != nil { panic(err) } return f } func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data") ! } ! func closeFile(f *os.File) { fmt.Println("closing") f.Close() } GBE
  • 31. (Semi)automatic Resource Management func main() { f := createFile("/tmp/defer.txt") defer closeFile(f) writeFile(f) } Run after the function completes. GBE
  • 34. • Every class in a package • Import classes explicitly - import java.util.Map • Import all classes in a package - import java.util.* • Statically import class static members: - import static java.lang.Math.PI - import static java.lang.Math.* Java Packaging
  • 35. • All types and functions belong to a package. • Every source file must declare its package. • Import packages to gain access to exported members. Go Packaging
  • 36. • public - any class in same package, or any importing class in a different package, can see • default (“package private”) - any class in same package can see • protected - any class in same package, or any subclass in a different package, can see • private - no class other than this can see • Scope indicated by prefixing name at declaration time. Java Scoping
  • 37. • exported - any code in an importing file can see - exported names start with uppercase letter - func Copy(src *[]byte, dest *[]byte) • non-exported - only code in the same package can see - non-exported names start with _ or lowercase letter - func copy(src *[]byte, dest *[]byte) - func _Copy(src *[]byte, dest *[]byte) Go Scoping
  • 38. • Conventional correspondence to directory paths (e.g. com.ms.foo should be at src/com/ms/foo) - tools expect this! • Package paths do not have to be unique at compile or runtime (first dependency found/loaded wins!) • Conventional correspondence to URL of author (e.g. my domain is www.mattstine.com, so my packages names start with com.mattstine) - but no actual relationship to source code location! Java Naming
  • 39. • Conventional correspondence to directory paths (e.g. github.com/go-martini/ martini should be at src/github.com/go-martini/martini) - tools expect this! • Package paths MUST BE UNIQUE across a $GOPATH. • Package names do not have to be unique. • Referring to imported names must be qualified by package name (e.g. sql.DB not just DB)… can locally alias (e.g. import dbstuff “database/sql”) • Conventional correspondence to URL of code location (e.g. import http://github.com/ joefitzgerald/cfenv as import “github.com/joefitzgerald/cfenv"). • Can “go get” remote packages - supports Git, SVN, Mercurial, Bazaar. Go Naming
  • 40. • Java admits: - circular package dependencies - dead imports • Go rejects: - circular package dependencies - dead imports Miscellany
  • 42.
  • 43.
  • 44. For realz this time…
  • 45. structs FTW type Point struct { X, Y float64 } Define a type. Give it a name. This type is a struct. (you can actually define others!) Add stuff! (upcase exports apply here too!)
  • 46. Methods are Functions! func (p Point) Translate(xDist float64, yDist float64) Point { return Point{p.X + xDist, p.Y + yDist} } Receiver argument! Can define methods on pointers or values.
  • 47. composition FTW type Point struct { X, Y float64 } ! const ( BLUE = iota RED = iota GREEN = iota ) ! type ColorPoint struct { Point Point Color int } Define an enumerated constant (closest to Java enum). A ColorPoint has-a Point!
  • 48. • I have Points. • I have ColorPoints. • ColorPoints are like Points, but they are not Points. • But I want to compute the euclidean distance between them. • What to do? Problem
  • 49.
  • 50. Interfaces Group Behaviors type Positioner interface { Coordinates() Point } ! type Distancer interface { DistanceTo(p Positioner) float64 }
  • 51. It’s all about satisfaction… Java = explicit ! Go = implicit
  • 52. Calculating Distance func distanceBetween(a Positioner, b Positioner) float64 { p := a.Coordinates() q := b.Coordinates() sqOfXDist := math.Pow(p.X-q.X, 2) sqOfYDist := math.Pow(p.Y-q.Y, 2) return math.Sqrt(sqOfXDist + sqOfYDist) }
  • 53. Point Satisfies Distancer and Positioner func (p Point) Coordinates() Point { return p } ! func (p Point) DistanceTo(pos Positioner) float64 { return distanceBetween(p, pos) }
  • 54. ColorPoint Satisfies Distancer and Positioner func (cp ColorPoint) Coordinates() Point { return cp.Point } ! func (cp ColorPoint) DistanceTo(pos Positioner) float64 { return distanceBetween(cp, pos) }
  • 56. Animal Satisfies Distancer and Positioner func (a Animal) Coordinates() point.Point { return point.Point{X: a.X, Y: a.Y} } ! func (a Animal) DistanceTo(pos point.Positioner) float64 { thing := pos.Coordinates() sqOfXDist := math.Pow(a.X-thing.X, 2) sqOfYDist := math.Pow(a.Y-thing.Y, 2) return math.Sqrt(sqOfXDist + sqOfYDist) }
  • 57. Go! p = point.Point{X: 1, Y: 2} q := point.ColorPoint{Point: point.Point{X: 1, Y: 4}, Color: point.BLUE} ! fmt.Printf("Dist b/w p and q = %vn", p.DistanceTo(q)) fmt.Printf("Dist b/w q and p = %vn", q.DistanceTo(p)) ! penguin := animal.Animal{Name: "penguin", X: 1, Y: 1} seal := animal.Animal{Name: "seal", X: 1, Y: 4} ! fmt.Printf("Dist b/w penguin and seal = %vn", penguin.DistanceTo(seal)) fmt.Printf("Dist b/w penguin and point = %vn", penguin.DistanceTo(p))
  • 59. • Parallelism = leveraging simultaneous execution of work to perform many things at once. Limited to number of processors/cores you have. • Concurrency = composition of work to manage many things at once. No theoretical limit. • Rob Pike: “Concurrency is Not Parallelism”
 http://www.youtube.com/watch?v=cN_DpYBzKso Concurrency vs Parallelism
  • 60. • Java - Threads - OS managed - Share address space with other threads in same process • Go - Goroutines - user-space managed by language runtime - multiplexed onto pool of OS threads Parallelism - How?
  • 61. • Java - Shared memory - Locking • Go - Can share memory (see http://golang.org/pkg/sync) - But there is a better way! Synchronization?
  • 62. – http://golang.org/doc/effective_go.html “Do not communicate by sharing memory; instead, share memory by communicating.”
  • 63. Goroutines func f(from string) { for i := 0; i < 3; i++ { fmt.Println(from, ":", i) } } ! func main() { f("direct") ! go f("goroutine") ! go func(msg string) { fmt.Println(msg) }("going") } GBE Synchronous Asynchronous Asynchronous and Anonymous
  • 64. Channels func main() { messages := make(chan string) ! go func() { messages <- "ping" }() ! msg := <-messages fmt.Println(msg) } GBE Create a new channel. Sending Receiving
  • 65. Channel Buffering func main() { messages := make(chan string, 2) ! messages <- "buffered" messages <- "channel" ! fmt.Println(<-messages) fmt.Println(<-messages) } GBE Make a channel that will buffer two values. Send twice Receive twice
  • 66. Channel Synchronization func worker(done chan bool) { fmt.Print("working...") time.Sleep(time.Second) fmt.Println("done") done <- true } ! func main() { done := make(chan bool, 1) go worker(done) <-done } GBE Notify receive that I’m done. Run worker on a goroutine, pass “done” channel. Block until msg received!
  • 67. Select c1 := make(chan string) c2 := make(chan string) ! go func() { time.Sleep(time.Second * 1) c1 <- "one" }() go func() { time.Sleep(time.Second * 2) c2 <- "two" }() GBE Create two channels. Create two goroutines; each sends message to different channel.
  • 68. Select for i := 0; i < 2; i++ { select { case msg1 := <-c1: fmt.Println("received", msg1) case msg2 := <-c2: fmt.Println("received", msg2) } } GBE Await both messages simultaneously! Print each as it arrives!
  • 69. Closing Channels jobs := make(chan int, 5) done := make(chan bool) ! go func() { for { j, more := <-jobs if more { fmt.Println("received job", j) } else { fmt.Println("received all jobs") done <- true return } } }() GBE Job channel for sending work. Done channel to indicate all work complete. Receive jobs - more will be false if jobs is closed. If no more jobs, say that I’m done!
  • 70. Closing Channels for j := 1; j <= 3; j++ { jobs <- j fmt.Println("sent job", j) } close(jobs) fmt.Println("sent all jobs") ! <-done GBE Send the jobs to the worker. Close the jobs channel. Block until the worker is finished.
  • 71. Range Over Channels func main() { queue := make(chan string, 2) queue <- "one" queue <- "two" close(queue) ! for elem := range queue { fmt.Println(elem) } } GBE Pull messages off channel for each iteration of the loop.
  • 72. • Features and Idioms • Packaging / Modularity • Types / OOP / Interfaces • Concurrency Contrasts with Java
  • 73. Thank You!!! Matt Stine (@mstine) Cloud Foundry Platform Engineer at Pivotal matt.stine@gmail.com http://www.mattstine.com OFFICE HOURS Wednesday, 2:30 - 3:10 PM Expo Hall (Table A)
  • 74. Code samples marked “GBE” at https://gobyexample.com are by Mark McGranaghan and are Creative Commons Attribution 3.0 Unported licensed (http://creativecommons.org/licenses/by/3.0). ! The Go Gopher logo was created by Renee French and is Creative Commons Attribution 3.0 Unported licensed (http:// creativecommons.org/licenses/by/3.0). ! The Java Duke logo is BSD licensed (http://opensource.org/licenses/bsd-license.php).