Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I don't understand why Future doesn't work? Can someone help me? I got this code from official scala website. It's doesn't compile error Future.type doesn't take parameters
import scala.concurrent.Future
import java.lang.Thread.sleep
object Future extends App {
def getStockPrice(stockSymbol: String): Future[Double] = Future {
val r = scala.util.Random
val randomSleepTime = r.nextInt(3000)
val randomPrice = r.nextDouble * 1000
sleep(randomSleepTime)
randomPrice
}
}
Change the object name from Future to something else. You also need an implicit ExecutionContext available. Following will work.
import scala.concurrent.Future
import java.lang.Thread.sleep
import scala.concurrent.ExecutionContext.Implicits.global
object FutureApp extends App {
def getStockPrice(stockSymbol: String): Future[Double] = Future {
val r = scala.util.Random
val randomSleepTime = r.nextInt(3000)
val randomPrice = r.nextDouble * 1000
sleep(randomSleepTime)
randomPrice
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a text file looks like below
a~ϕ~b~ϕ~c~ϕ~d~ϕ~e
1~ϕ~2~ϕ~3~ϕ~4~ϕ~5
I want the the below output to be written into the text file
a,b,c,d,e
1,2,3,4,5
Here is a another approach which replaces ~ϕ~ seperator with , using a temporary file to store the intermediate results of replacement:
import java.io.{File, PrintStream}
import scala.io.{Codec, Source}
object ReplaceIOStringExample {
val Sep = "~ϕ~"
def main(args: Array[String]): Unit = {
replaceFile("/tmp/test.data")
}
def replaceFile(path: String) : Unit = {
val inputStream = Source.fromFile(path)(Codec.UTF8)
val outputLines = inputStream.getLines()
new PrintStream(path + ".bak") {
outputLines.foreach { line =>
val formatted = line.split(Sep).mkString(",") + "\n"
write(formatted.getBytes("UTF8"))
}
}
//delete old file
new File(path).delete()
//rename .bak file to the initial file name
new File(path + ".bak").renameTo(new File(path))
}
}
Notice that val outputLines = inputStream.getLines() will return an Iterator[String] which means that we read the file lazily. This approach allows us to format each line and write it back to the output file avoiding storing the whole file in the memory.
You can replace with replaceAll with regular expression or
"a~ϕ~b~ϕ~c~ϕ~d~ϕ~e".filter(c => c.isLetter || c.isDigit).mkString(",")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I currently have a Scala echo server, how to do I implement Akka into the code so it would serve HTML files that I've implemented?
Don't even know how to begin to work this out, would I have to import something like an Akka thing? Or to change my dependencies? So instead of using imports Java and Scala would I change it to Akka instead?
My echo server
import java.net._
import java.io._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.Breaks
object EchoServer {
def read_and_write(in: BufferedReader, out: BufferedWriter): Unit = {
out.write(in.readLine())
out.flush()
in.close()
out.close()
}
def serve(server: ServerSocket): Unit = {
val s = server.accept()
val in = new BufferedReader(new InputStreamReader(s.getInputStream))
val out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream))
read_and_write(in, out)
s.close()
}
def getListOfFiles(dir: String): List[File] = {
val file = new File(dir)
if (file.exists && file.isDirectory) {
file.listFiles.filter(_.isFile).toList
} else {
List[File]()
}
}
def main(args: Array[String]) {
val server = new ServerSocket(9999)
var readString = "C:\\Users\\Desktop\\EchoServer\\src\\main\\htmlFiles"
println("What file are you looking for with extension?")
implicit val ec = ExecutionContext.global
while (true) {
Future {
implicit val ec = ExecutionContext.global
val userInput = scala.io.StdIn.readLine()
val result = getListOfFiles(readString)
val loop = new Breaks
try {
result.foreach { file =>
if (file.getName.endsWith(".html") == (userInput.endsWith(".html"))) {
if (file.getName.equals(userInput)) {
println(file.getName + " file found")
}
else {
println("file not found")
}
}
}
}
catch {
case e: FileNotFoundException => println("Couldn't find that file.")
}
serve(server)
}
}
}
}
I had implemented futures, not sure if it serves HTML files correctly even. How would I change this to akka concurrency?
I have an Rest API provided by akka-http. In some cases I need to get data from an external database (Apache HBase), and I would like the query to fail if the database takes too long to deliver the data.
One naïve way is to wrap the call inside a Future and then block it with an Await.result with the needed duration.
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
object AsyncTest1 extends App {
val future = Future {
getMyDataFromDB()
}
val myData = Await.result(future, 100.millis)
}
The seems to be inefficient as this implementation needs two threads. Is There an efficient way to do this ?
I have another use case where I want to send multiple queries in parallel and then aggregates the results, with the same delay limitation.
val future1 = Future {
getMyDataFromDB1()
}
val future2 = Future {
getMyDataFromDB2()
}
val foldedFuture = Future.fold(
Seq(future1, future2))(MyAggregatedData)(myAggregateFunction)
)
val myData = Await.result(foldedFuture, 100.millis)
Same question here, what is the most efficient way to implement this ?
Thanks for your help
One solution would be to use Akka's after function which will let you pass a duration, after which the future throws an exception or whatever you want.
Take a look here. It demonstrates how to implement this.
EDIT:
I guess I'll post the code here in case the link gets broken in future:
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
import akka.actor.ActorSystem
import akka.pattern.after
val system = ActorSystem("theSystem")
lazy val f = future { Thread.sleep(2000); true }
lazy val t = after(duration = 1 second, using = system.scheduler)(Future.failed(new TimeoutException("Future timed out!")))
val fWithTimeout = Future firstCompletedOf Seq(f, t)
fWithTimeout.onComplete {
case Success(x) => println(x)
case Failure(error) => println(error)
}
I saw something
import java.util.concurrent.Executors
import scala.concurrent.{ExecutionContext, Await, Future}
import scala.concurrent.duration._
val numJobs = 50000
var numThreads = 10
// customize the execution context to use the specified number of threads
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(numThreads))
// define the tasks
val tasks = for (i <- 1 to numJobs) yield Future {
// do something more fancy here
i
}
// aggregate and wait for final result
val aggregated = Future.sequence(tasks)
val oneToNSum = Await.result(aggregated, 15.seconds).sum
However, this doesn't finish with Success.
I dont know why. I think maybe the Await.result is cause.
Please notice the solution.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to Scala and I have some URLs. I need to check whether those resources referenced by URLs are working or not? How can I achieve this with Scala?
Since a URL is just a virtual reference to a web resource - it always works. ;)
Additionally, you can read one line from the resource as text:
try {
val text = Source.fromUrl(new java.net.URL(someString)).getLine
} catch {
case java.io.IOException => // do something ...
}
OR read all lines from the resource as text:
try {
val source = Source.fromUrl(new java.net.URL(someString))
for (line <- source) {
println(line)
// do anything you like with each line of text
}
} catch {
case java.io.IOException => // do something ...
}
Or you can use java classes to connect to the resource and read it's length, etc ...:
try {
val connection = (new java.net.URL(someString)).openConnection
connection.connect;
val l = connection.getContentLength
// use the connection anyway you like
} catch {
case java.io.IOException => // do something ...
}
You will need to use an http access library to try and access the URL. Using play2's WS
import play.api.libs.ws.WS
val futureResponse:Future[Response] = WS.url("http://www.example.com/404.html").get()
then you can either use monadic operations to read the response and react
futureResponse.map {response => response.status==404} //will return a Future[Boolean]
or you can block until you actually have the response :
import scala.concurrent._
import scala.concurrent.duration._
val response =Await.result(futureResponse, 5 seconds)
if(response.status==404) {
???
}else{
???
}
There are other HTTP clients for scala such as Dispatch
I don't think there's an easy way to do this with Scala's standard library. But there are several other libraries that help you with your problem.
I'll give you an explanation that shows how to do this with Spray. This solution has the advantage that it is non-blocking, but as you are new to Scala, the usage of Futures might be new to you.
First you need to add some dependencies to your project. The easiest way is if you use SBT. Add the following lines to your build.sbt.
resolvers += "spray repo" at "http://repo.spray.io"
// Dependencies
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.2.3"
libraryDependencies += "io.spray" % "spray-client" % "1.2.0"
Now the source code of your program looks quite easy and is also non-blocking:
import akka.actor.ActorSystem
import spray.http._
import spray.client.pipelining._
import scala.concurrent.Future
import scala.util.{ Success, Failure }
object HTTPTest extends App {
implicit val system = ActorSystem("http-test")
import system.dispatcher // execution context for futures
// take an http request and return a future of http response
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive
// this method will give you *only* the status code for a URL as a Future
def getStatusFor(url: String): Future[Int] =
pipeline(Get(url)).map { x => x.status.intValue }
// use it this way
getStatusFor("http://server.org/help").onComplete {
case Success(statusCode) => println(statusCode)
case Failure(err) => // do something with the exception
}
}
Does this help?