Groovy web console

subscribe to the feed Subscribe
to this
site

Concurrent Stock Quotation with Result Actor

Published 1 decade ago by Vaclav Pech with tags gparallelizer concurrent actors
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
import static org.gparallelizer.actors.pooledActors.PooledActors.actor

def getYearEndClosing(String symbol, int year) {
    def url = "http://ichart.finance.yahoo.com/table.csv?s=$symbol&a=11&b=01&c=$year&d=11&e=31&f=$year&g=m;ignore=.csv"
    def data = url.toURL().text
    def price = data.split("\n")[1].split(",")[4].toDouble()
    Thread.sleep(1000); // slow down internet
    [symbol:symbol, price:price]
}

def symbols = ['AAPL', 'GOOG', 'IBM', 'JAVA', 'MSFT']

def observer
observer = actor {
    def start = System.nanoTime()
    symbols.each {stock -> actor { observer << getYearEndClosing(stock, 2008) }.start() }
    def top = [symbol:"", price:0.0]
    def quoteNum = 0
    loop {
        quoteNum += 1
        if (quoteNum <= symbols.size()) {
            react {quote ->
                println "Received a quote for ${quote.symbol} priced ${quote.price}"
                if (quote.price > top.price) top = quote
            }
        } else {
            def end = System.nanoTime()

            println "Top stock is ${top.symbol} with price ${top.price}"
            println "Time taken ${(end - start) / 10000000000.0}"
            stop()
        }
    }
}.start()

observer.join()