ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Semaphore 를 사용해 최대 maxConcurrent 개의 Future만 실행되도록 제한
    scala/basic 2025. 3. 13. 10:28

    내가 작성

    package com.naver.search.web
    
    import java.util.concurrent.Semaphore
    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.concurrent.{Await, Future}
    
    object SemaphoreFutureTest {
    	def semFuture[T](f: => T, n: Int): Future[T] = {
    		val sem = new Semaphore(n)
    		Future {
    			try {
    				sem.acquire()
    				f
    			} finally {
    				sem.release()
    			}
    		}
    	}
    
    	def f(x: Int): Int = {
    		Thread.sleep(1000)
    		println(x)
    		x * 10
    	}
    
    
    	def main(args: Array[String]): Unit = {
    		val futures: Seq[Future[Int]] = (1 to 9).map { x =>
    			semFuture(f(x), 2)
    		}
    
    		val r: Future[Seq[Int]] = Future.sequence(futures)
    		val ints: Seq[Int] = Await.result(r, scala.concurrent.duration.Duration.Inf)
    		ints.foreach(println)
    	}
    }

     

     

    AI 작성 코드

    import scala.concurrent.{Future, ExecutionContext}
    import scala.concurrent.duration._
    import java.util.concurrent.Semaphore
    
    implicit val ec: ExecutionContext = ExecutionContext.global
    
    def limitConcurrentFutures[T](futures: List[() => Future[T]], maxConcurrent: Int): Future[List[T]] = {
      val semaphore = new Semaphore(maxConcurrent)
    
      val limitedFutures = futures.map { futureFunc =>
          semaphore.acquire()
          try {
            futureFunc()
          } finally {
            semaphore.release()
          }
      }
    
      Future.sequence(limitedFutures)
    }
    
    // 사용 예제
    val tasks: List[() => Future[Int]] = List(
      () => Future { Thread.sleep(1000); 1 },
      () => Future { Thread.sleep(1000); 2 },
      () => Future { Thread.sleep(1000); 3 },
      () => Future { Thread.sleep(1000); 4 }
    )
    
    val result: Future[List[Int]] = limitConcurrentFutures(tasks, 2)
    result.onComplete(println)

    댓글

Designed by Tistory.