SlideShare a Scribd company logo
Go / Scala
Implementation of go language constructions
in scala
Ruslan Shevchenko
<ruslan@shevchenko.kiev.ua>
https://github.com/rssh/scala-gopher
Whats in go ?

scope

( defer/ panic / destroy )

parallelism

channels

select statement

Differences from 'native' scala approach

How to implement go variant
Future directions...
Scope
def copy(inf: File, outf: File): Long = goScope {
val in = new FileInputStream(inf)
defer{ in.close() }
val out = new FileOutputStream(outf);
defer{ out.close() }
out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue)
}
def copy(inf: File, outf: File): Long =
{
val in = new FileInputStream(inf)
try {
val out = new FileOutputStream(outf)
try {
out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue)
} finally {
out.close();
}
} finally {
in.close();
}
}
Old way:
Traditional way:
def copy(inf: File, outf: File): Long =
{
val in = new FileInputStream(inf)
try {
val out = new FileOutputStream(out)
try {
out.getChannel() transferFrom(in.getChannel(), 0,Long.MaxValue)
} finally {
out.close();
}
} finally {
in.close();
}
}
def copy(inf: File, outf: File): Long = goScope {
val in = new FileInputStream(inf)
defer{ in.close() }
val out = new FileOutputStream(outf);
defer{ out.close() }
out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue)
}
Go way
try
try
try
finally
finally
finally
op/defer
How this done is scala:

Macroses

Call-by-name-params

Traditional try/cath
goScope = .... (macro wich rewrite arg)
defer => @compileTimeOnly
def copy(inf: File, outf: File): Long = {
val sc0 = new ScopeContext();
sc0.eval {
val in = new FileInputStream(inf)
sc0.pushDefer{ in.close() }
val out = new FileOutputStream(outf);
sc0.pushDefer{ out.close() }
out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue)
}
sc0.unwindDefers[Long]()
}
Unsugared:
Scope: defer / panic / recover

panic => throw new PanicException()

Recover => return
try {
....
} catch {
case ex: Exception =>
return x
}
defer{
.........
recover(x)
}
Implementation of 'go-like' language constructions in scala [english version]
Channels
Read:
go: channel -> x
Scala:
channel ~> x
x = channel ?
?!
??
Write
go: channel <- x
Scala:
channel <~ x
channel ! x
!! (immediatly)
!? (with timeout)
Implementation of 'go-like' language constructions in scala [english version]
Select
Channels connect execution flows
go func() {
for {
select {
case msg1 := <- c1:
fmt.Println(msg1)
case msg2 := <- c2:
fmt.Println(msg2)
}
}
}()
Go: typical pattern:
select inside for inside goroutine
go
for(s <- select) s match {
case c1 ~> (msg1: Msg1Type) => println(msg1)
case c2 ~>(msg2:Msg2Type) => println(msg2)
}
Scala Analog:
- implemented as foreach macros
- ~> pattern: require typing
- active queue
Open question: native non-macro syntax
Unsugared (simplicified) [1]:
go {
val s = new SelectContext();
s.addReader(c1) {
(msg1:Msg1Type) => println(msg1)
}
s.addReader(c2) {
(msg2:Msg2Type) => println(msg2)
}
s.run()
}
Unsugared (simplicified) [2]:
val scope = new ScopeContext();
val s = new SelectContext();
Future {
s.addReader(c1) {
(msg1:Msg1Type) => println(msg1)
}
s.addReader(c2) {
(msg2:Msg2Type) => println(msg2)
}
} map { s.runUnblocked() }
map { scope.finish() }
(Future work)
S
Just select:
for(s <- select.once) s match {
case c1 ~> (msg1: Msg1Type) => println(msg1)
case c2 ~>(msg2:Msg2Type) => println(msg2)
}
select {
case msg1 := <- c1: fmt.Println(msg1)
case msg2 := <- c2: fmt.Println(msg2)
}
GO
SCALA
Internal implementation:

Active channel

Channel = [Blocked Query + Execution Context ]

Coordination primitives + wait for select

Count down latch

Memory barrier

Extensions over Go model

async operations

context shutdown.
val consumer = go {
for(s <- select) {
s match {
case `channel` ~> (i:Int) =>
sum = sum + i
if (i==1000) s.shutdown()
}
}
sum
}
Future[Int]
Akka
(Erlang-like actors)
Channels (go-like)

Reactive

No blocking operations

Request/Reply paradigm.

Mailbox overflow
on overload

Handle something.

Flow oriented

Wait is normal
(switch during wait)

One-direction pipe paradigm

wait on send
On overload

Compute something
x1, x2, x3, ............
x1*y1, x2*y2, x3*y3, ............
y1, y2, y3, ............
go {
while(;) {
val x = channelX ?
val y = channelY ?
channelZ ! x*y
}
}
Example: Easy with channels, hard with Akka
bindWrite
bindRead
? [blocking operation]
Future directions

Redefining of base primitivies
[select in loop in go] is too fundamental, to be
combination of 3 constructions.

Native non-macro syntax

Make scala type inference works

Pluggable implementations

Optimize corner cases
Pluggable implementations.

Exists many strategies.
(current implemented is not best)

Schedule/callback instead waits

Play with own dispatcher

.....

Performance tests,

Implement/Prototype/Test loop,

Problems:

Lack of import-based configuration in scala

@exported import

Community help needed.
Rewriting blocking API into reactive
- like CPS (continuations passing style)
go {
...
val x = channelX ?
val y = channelY ?
channelZ ! x*y
...
}
go { .....
channelX.read map { x =>
channelY.read map { y =>
channelZ.write map { ch =>
ch <~! x*y
} } }
}
}
someCollection foldLeft {
(s,x) => s + (x* channel ?)
}
Problem – same as with CPS:
- foldLeft – implemented not here.
- foreach
for(x <- something) channel <~~ x
Continuations not supported directly by JVM
Continuations in JVM
- Patched JVM
- Byte-code rewriting.
- Do nothing – thread pools now big
(utilize wait by running
Flow of non-blocking tasks here)
The Da Vinci machine
http://openjdk.java.net/projects/mlvm/index.html
AVIAN VM
http://oss.readytalk.com/avian/
Someday everything will be fine.
For now - here is a cat
Continuations: Bytecode rewriting.
Frames:
Let's save frame during function end, instead deleting one.
foldLeft
? channel
+
*
Continuations: Bytecode rewriting.
Frames:
foldLeft
+
*
Continuations: Bytecode rewriting.
Frames:
Suspended
CPS transformation on bytecode level
foldLeft
+
*
Channel ?
Community help needed.
https://github.com/rssh/scala-gopher

Build examples of typical usage.

Instrument ones for performance tests

Provide better implementations.
Let's think together. Thanks for attention.
Ruslan Shevchenko
<Ruslan@Shevchenko.Kiev.UA>

More Related Content

PPTX
Anti patterns
PPTX
Lambda выражения и Java 8
PDF
Clojure+ClojureScript Webapps
PDF
scala-gopher: async implementation of CSP for scala
KEY
Beauty and Power of Go
PDF
Listing for MyStringFunctions
PDF
Concurrency in Golang
PPTX
Anti patterns
Lambda выражения и Java 8
Clojure+ClojureScript Webapps
scala-gopher: async implementation of CSP for scala
Beauty and Power of Go
Listing for MyStringFunctions
Concurrency in Golang

What's hot (20)

PDF
Full Stack Clojure
PDF
Tcl2012 8.6 Changes
PPTX
STACK || FUNCTION WRITING BASED ON STACK || DATA STRUCTURE || LINKED LIST || ...
PDF
Are we ready to Go?
PDF
Go Concurrency
PDF
The Ring programming language version 1.10 book - Part 93 of 212
PDF
Rcpp11 useR2014
PDF
Антон Бикинеев, Reflection in C++Next
PDF
ClojureScript loves React, DomCode May 26 2015
PDF
Golang Channels
PDF
The Ring programming language version 1.6 book - Part 37 of 189
PDF
Modern c++ Memory Management
PPTX
Loops in R
PPTX
Python
PDF
Rcpp11 genentech
PDF
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
PDF
R/C++ talk at earl 2014
PDF
FS2 for Fun and Profit
PDF
Protocol handler in Gecko
PDF
C c++-meetup-1nov2017-autofdo
Full Stack Clojure
Tcl2012 8.6 Changes
STACK || FUNCTION WRITING BASED ON STACK || DATA STRUCTURE || LINKED LIST || ...
Are we ready to Go?
Go Concurrency
The Ring programming language version 1.10 book - Part 93 of 212
Rcpp11 useR2014
Антон Бикинеев, Reflection in C++Next
ClojureScript loves React, DomCode May 26 2015
Golang Channels
The Ring programming language version 1.6 book - Part 37 of 189
Modern c++ Memory Management
Loops in R
Python
Rcpp11 genentech
CodeFest 2014. Axel Rauschmayer — JavaScript’s variables: scopes, environment...
R/C++ talk at earl 2014
FS2 for Fun and Profit
Protocol handler in Gecko
C c++-meetup-1nov2017-autofdo
Ad

Viewers also liked (12)

PDF
Csp scala wixmeetup2016
PDF
Web architecture - overview of techniques.
PDF
Ruslan.shevchenko: most functional-day-kiev 2014
PDF
Why scala is not my ideal language and what I can do with this
PDF
Few simple-type-tricks in scala
PDF
Java & low latency applications
PDF
Jslab rssh: JS as language platform
PDF
Scala jargon cheatsheet
PDF
SE 20016 - programming languages landscape.
PDF
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
PDF
Behind OOD: domain modelling in post-OO world.
PDF
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Csp scala wixmeetup2016
Web architecture - overview of techniques.
Ruslan.shevchenko: most functional-day-kiev 2014
Why scala is not my ideal language and what I can do with this
Few simple-type-tricks in scala
Java & low latency applications
Jslab rssh: JS as language platform
Scala jargon cheatsheet
SE 20016 - programming languages landscape.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Behind OOD: domain modelling in post-OO world.
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ad

Similar to Implementation of 'go-like' language constructions in scala [english version] (20)

PDF
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
PDF
Scala in Places API
PPT
Concurrency in go
PDF
Introduction to Scalding and Monoids
PDF
A Recovering Java Developer Learns to Go
PDF
Lecture 3
PDF
Java 8 Workshop
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
PDF
Twig Templating
PDF
Clojure 1.1 And Beyond
PPTX
Modern_Java_Workshop manjunath np hj slave
PDF
Goroutines and Channels in practice
PDF
Functional Smalltalk
PPT
Lecture#6 functions in c++
PDF
Refactoring to Macros with Clojure
PPT
Laurens Van Den Oever Xopus Presentation
PDF
From Java to Scala - advantages and possible risks
PDF
The what over the how (another way on android development with kotlin)
PDF
2014 holden - databricks umd scala crash course
PDF
N flavors of streaming
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Scala in Places API
Concurrency in go
Introduction to Scalding and Monoids
A Recovering Java Developer Learns to Go
Lecture 3
Java 8 Workshop
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Twig Templating
Clojure 1.1 And Beyond
Modern_Java_Workshop manjunath np hj slave
Goroutines and Channels in practice
Functional Smalltalk
Lecture#6 functions in c++
Refactoring to Macros with Clojure
Laurens Van Den Oever Xopus Presentation
From Java to Scala - advantages and possible risks
The what over the how (another way on android development with kotlin)
2014 holden - databricks umd scala crash course
N flavors of streaming

More from Ruslan Shevchenko (16)

PDF
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
PDF
Svitla talks 2021_03_25
PDF
Akka / Lts behavior
PDF
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
PDF
Scala / Technology evolution
PDF
{co/contr} variance from LSP
PDF
R ext world/ useR! Kiev
PDF
Programming Languages: some news for the last N years
PDF
R scala 17_05_2014
ODP
Javascript in modern scala backend. [russian]
PDF
Osdn2013 rssh
ODP
implementation of 'go'-like language constructions in scala (russian)
ODP
Play/Scala as application platform (for http://wbcamp.in.ua 2013)
ODP
Iteratee explained.
ODP
Annotated imports
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Svitla talks 2021_03_25
Akka / Lts behavior
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
Scala / Technology evolution
{co/contr} variance from LSP
R ext world/ useR! Kiev
Programming Languages: some news for the last N years
R scala 17_05_2014
Javascript in modern scala backend. [russian]
Osdn2013 rssh
implementation of 'go'-like language constructions in scala (russian)
Play/Scala as application platform (for http://wbcamp.in.ua 2013)
Iteratee explained.
Annotated imports

Recently uploaded (20)

PPTX
A Presentation on Artificial Intelligence
PDF
Empathic Computing: Creating Shared Understanding
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PPTX
Machine Learning_overview_presentation.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Electronic commerce courselecture one. Pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
A Presentation on Artificial Intelligence
Empathic Computing: Creating Shared Understanding
Spectral efficient network and resource selection model in 5G networks
gpt5_lecture_notes_comprehensive_20250812015547.pdf
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
Machine Learning_overview_presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
The Rise and Fall of 3GPP – Time for a Sabbatical?
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
A comparative analysis of optical character recognition models for extracting...
Electronic commerce courselecture one. Pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Review of recent advances in non-invasive hemoglobin estimation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
“AI and Expert System Decision Support & Business Intelligence Systems”
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows

Implementation of 'go-like' language constructions in scala [english version]

  • 1. Go / Scala Implementation of go language constructions in scala Ruslan Shevchenko <[email protected]> https://github.com/rssh/scala-gopher
  • 2. Whats in go ?  scope  ( defer/ panic / destroy )  parallelism  channels  select statement  Differences from 'native' scala approach  How to implement go variant Future directions...
  • 3. Scope def copy(inf: File, outf: File): Long = goScope { val in = new FileInputStream(inf) defer{ in.close() } val out = new FileOutputStream(outf); defer{ out.close() } out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue) } def copy(inf: File, outf: File): Long = { val in = new FileInputStream(inf) try { val out = new FileOutputStream(outf) try { out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue) } finally { out.close(); } } finally { in.close(); } } Old way:
  • 4. Traditional way: def copy(inf: File, outf: File): Long = { val in = new FileInputStream(inf) try { val out = new FileOutputStream(out) try { out.getChannel() transferFrom(in.getChannel(), 0,Long.MaxValue) } finally { out.close(); } } finally { in.close(); } }
  • 5. def copy(inf: File, outf: File): Long = goScope { val in = new FileInputStream(inf) defer{ in.close() } val out = new FileOutputStream(outf); defer{ out.close() } out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue) } Go way
  • 7. How this done is scala:  Macroses  Call-by-name-params  Traditional try/cath goScope = .... (macro wich rewrite arg) defer => @compileTimeOnly
  • 8. def copy(inf: File, outf: File): Long = { val sc0 = new ScopeContext(); sc0.eval { val in = new FileInputStream(inf) sc0.pushDefer{ in.close() } val out = new FileOutputStream(outf); sc0.pushDefer{ out.close() } out.getChannel() transferFrom(in.getChannel(), 0, Long.MaxValue) } sc0.unwindDefers[Long]() } Unsugared:
  • 9. Scope: defer / panic / recover  panic => throw new PanicException()  Recover => return try { .... } catch { case ex: Exception => return x } defer{ ......... recover(x) }
  • 11. Channels Read: go: channel -> x Scala: channel ~> x x = channel ? ?! ?? Write go: channel <- x Scala: channel <~ x channel ! x !! (immediatly) !? (with timeout)
  • 14. go func() { for { select { case msg1 := <- c1: fmt.Println(msg1) case msg2 := <- c2: fmt.Println(msg2) } } }() Go: typical pattern: select inside for inside goroutine
  • 15. go for(s <- select) s match { case c1 ~> (msg1: Msg1Type) => println(msg1) case c2 ~>(msg2:Msg2Type) => println(msg2) } Scala Analog: - implemented as foreach macros - ~> pattern: require typing - active queue Open question: native non-macro syntax
  • 16. Unsugared (simplicified) [1]: go { val s = new SelectContext(); s.addReader(c1) { (msg1:Msg1Type) => println(msg1) } s.addReader(c2) { (msg2:Msg2Type) => println(msg2) } s.run() }
  • 17. Unsugared (simplicified) [2]: val scope = new ScopeContext(); val s = new SelectContext(); Future { s.addReader(c1) { (msg1:Msg1Type) => println(msg1) } s.addReader(c2) { (msg2:Msg2Type) => println(msg2) } } map { s.runUnblocked() } map { scope.finish() } (Future work) S
  • 18. Just select: for(s <- select.once) s match { case c1 ~> (msg1: Msg1Type) => println(msg1) case c2 ~>(msg2:Msg2Type) => println(msg2) } select { case msg1 := <- c1: fmt.Println(msg1) case msg2 := <- c2: fmt.Println(msg2) } GO SCALA
  • 19. Internal implementation:  Active channel  Channel = [Blocked Query + Execution Context ]  Coordination primitives + wait for select  Count down latch  Memory barrier  Extensions over Go model  async operations  context shutdown.
  • 20. val consumer = go { for(s <- select) { s match { case `channel` ~> (i:Int) => sum = sum + i if (i==1000) s.shutdown() } } sum } Future[Int]
  • 21. Akka (Erlang-like actors) Channels (go-like)  Reactive  No blocking operations  Request/Reply paradigm.  Mailbox overflow on overload  Handle something.  Flow oriented  Wait is normal (switch during wait)  One-direction pipe paradigm  wait on send On overload  Compute something
  • 22. x1, x2, x3, ............ x1*y1, x2*y2, x3*y3, ............ y1, y2, y3, ............ go { while(;) { val x = channelX ? val y = channelY ? channelZ ! x*y } } Example: Easy with channels, hard with Akka
  • 24. Future directions  Redefining of base primitivies [select in loop in go] is too fundamental, to be combination of 3 constructions.  Native non-macro syntax  Make scala type inference works  Pluggable implementations  Optimize corner cases
  • 25. Pluggable implementations.  Exists many strategies. (current implemented is not best)  Schedule/callback instead waits  Play with own dispatcher  .....  Performance tests,  Implement/Prototype/Test loop,  Problems:  Lack of import-based configuration in scala  @exported import  Community help needed.
  • 26. Rewriting blocking API into reactive - like CPS (continuations passing style)
  • 27. go { ... val x = channelX ? val y = channelY ? channelZ ! x*y ... } go { ..... channelX.read map { x => channelY.read map { y => channelZ.write map { ch => ch <~! x*y } } } } }
  • 28. someCollection foldLeft { (s,x) => s + (x* channel ?) } Problem – same as with CPS: - foldLeft – implemented not here. - foreach for(x <- something) channel <~~ x Continuations not supported directly by JVM
  • 29. Continuations in JVM - Patched JVM - Byte-code rewriting. - Do nothing – thread pools now big (utilize wait by running Flow of non-blocking tasks here)
  • 30. The Da Vinci machine http://openjdk.java.net/projects/mlvm/index.html AVIAN VM http://oss.readytalk.com/avian/
  • 31. Someday everything will be fine. For now - here is a cat
  • 32. Continuations: Bytecode rewriting. Frames: Let's save frame during function end, instead deleting one. foldLeft ? channel + *
  • 34. Continuations: Bytecode rewriting. Frames: Suspended CPS transformation on bytecode level foldLeft + * Channel ?
  • 35. Community help needed. https://github.com/rssh/scala-gopher  Build examples of typical usage.  Instrument ones for performance tests  Provide better implementations. Let's think together. Thanks for attention. Ruslan Shevchenko <[email protected]>