Yash Bhardwaj
Yash Bhardwaj

Reputation: 23

How to use Futures for Multithreading?

I am new to Scala. I am learning multi-threading in Scala. One way of Multi-threading in Scala is scala.actors but it is deprecated nowadays. So the new way is to use scala.concurrent or akka.actor. I want to use scala.concurrent. Scenario: I want to make a chat server which accepts connections of multiple clients simultaneously and responses back. the way I am trying to do is:

    while(true) {
      socket = serverSocket.accept()
      os = new PrintStream(socket.getOutputStream)
      br = new BufferedReader(new InputStreamReader(socket.getInputStream()))

      val newClient = Future {
        os.println("\n\nPlease Enter the Table name to be Extracted\t:")
        restr = br.readLine()

        println("data received from ["+socket.getInetAddress()+"] ["+socket.getPort()+"] and TableName ["+ restr +"]\n")
        new Extractor().extract(dbURL,userId,password,restr,os)
      }
     val clientFormed= newClient.isCompleted
      println("New Client Connection ? ["+clientFormed+"]")
    }

but after running the program The output says:

New Response made [false]

Means the Futures didn't Execute. Even the sleep is not working. I know I am lacking something here but can't figure it out.

UPDATE I know while(true) inside future is not the Correct way but while true is necessary for continuous run of server. I know my way is wrong. What I'm asking is: what is the correct way to do it?

Upvotes: 1

Views: 88

Answers (1)

C4stor
C4stor

Reputation: 8026

response is a future starting with a while(true). There is no way it can ever complete.

Upvotes: 3

Related Questions