TDT4165-Scala-Project/project_tasks/src/main/scala/Bank.scala

80 lines
2.3 KiB
Scala
Raw Normal View History

2022-11-18 14:31:09 +01:00
class Bank(val allowedAttempts: Integer = 3, val workers: Integer = 5) {
2022-10-14 12:51:19 +02:00
private val transactionsQueue: TransactionQueue = new TransactionQueue()
private val processedTransactions: TransactionQueue = new TransactionQueue()
2022-11-15 15:55:37 +01:00
private var processingThreadsStarted = false;
private val processingThreads: List[Thread] =
2022-11-18 14:31:09 +01:00
(1 to workers).map(_ => new Thread {
2022-11-15 15:55:37 +01:00
override def run = processTransactions
}).toList
2022-11-18 14:31:09 +01:00
private var addedTransactions = 0
2022-10-14 12:51:19 +02:00
2022-11-11 16:42:06 +01:00
def addTransactionToQueue(from: Account, to: Account, amount: Double): Unit = {
transactionsQueue.push(new Transaction(
transactionsQueue,
processedTransactions,
from,
to,
amount,
2022-11-18 14:31:09 +01:00
allowedAttempts,
2022-11-11 16:42:06 +01:00
))
2022-11-18 14:31:09 +01:00
addedTransactions += 1
processingThreadsStarted.synchronized({
if (!processingThreadsStarted) {
processingThreads.foreach(t => {
t.start
})
processingThreadsStarted = true;
}
})
2022-11-11 16:42:06 +01:00
}
2022-11-15 15:55:37 +01:00
// TODO
// project task 2
// create a new transaction object and put it in the queue
// spawn a thread that calls processTransactions
// This function is a worker that continuously
// pops elements from the queue and processes them.
// Multiple of these can be run on separate threads.
private def processTransactions: Unit = {
2022-11-18 14:31:09 +01:00
val maybeTrx = transactionsQueue.synchronized(
if (transactionsQueue.isEmpty) None else Some(transactionsQueue.pop)
)
2022-11-15 15:55:37 +01:00
2022-11-18 14:31:09 +01:00
maybeTrx match {
case Some(trx) => {
Main.thread(trx.run).join()
2022-11-15 15:55:37 +01:00
2022-11-18 14:31:09 +01:00
if (trx.status == TransactionStatus.PENDING) {
transactionsQueue.push(trx)
} else {
processedTransactions.push(trx)
}
2022-11-15 15:55:37 +01:00
}
2022-11-18 14:31:09 +01:00
case None => Thread.sleep(50)
2022-11-11 16:42:06 +01:00
}
2022-11-15 15:55:37 +01:00
processTransactions
2022-11-11 16:42:06 +01:00
}
2022-11-15 15:55:37 +01:00
// TODO
// project task 2
// Function that pops a transaction from the queue
// and spawns a thread to execute the transaction.
// Finally do the appropriate thing, depending on whether
// the transaction succeeded or not
2022-10-14 12:51:19 +02:00
def addAccount(initialBalance: Double): Account = {
new Account(this, initialBalance)
}
def getProcessedTransactionsAsList: List[Transaction] = {
processedTransactions.iterator.toList
}
}