2016-07-12 7 views
2

FS2Object Pool pattern을 구현하는 가장 좋은 방법을 찾으려고합니다.FS2를 사용하는 개체 풀 패턴

class MyPrinter { 
    import scala.util.Random.nextInt 
    Thread.sleep(5000 + nextInt(1000)) 
    def doStuff(s: String): Unit = { 
    println(s) 
    Thread.sleep(1000 + nextInt(1000)) 
    } 
    def releaseResources(): Unit = 
    println("Releasing resources") 
} 

n 프린터의 풀 (pool)을 기본으로하는 Stream[Task, MyPrinter]을 할 수있는 가장 좋은 방법은 무엇입니까 :

은의 우리는 다음과 같은 MyPrinter 정의가 있다고 가정 해 봅시다? 스트림이 끝나면 releaseResources을 호출하여 모든 기본 리소스를 적절하게 해제해야합니다.

보너스 질문 : 프린터가 어떤 이유로 종료되면 풀에 새 프린터를 만들 수 있습니까?

답변

3

내가 질문을 가지고 있는지,하지만 방법이

implicit val S = Strategy.fromFixedDaemonPool(10, "pooling") 

val queue = new LinkedBlockingDeque[MyPrinter]() 
queue.add(new MyPrinter) 
queue.add(new MyPrinter) 

Stream.repeatEval(Task.delay(queue.take())) 
    .map(p => try p.doStuff("test") finally { 
    p.releaseResources() 
    queue.put(p) 
    }) 
    .take(10) 
    .runLog 
    .unsafeRun() 

https://commons.apache.org/proper/commons-pool/

UPD로 대체 할 수있다 : 각 "자원"을 처리하려면

동시에 :

concurrent.join(10)(
    Stream 
    .repeatEval(Task.delay(queue.take())) 
    .map(p => Stream.eval(Task.delay(p.doStuff("test")) 
    .map(_ => p /* done with this resource */))) 
).map(p => { p.releaseResources(); queue.put(p) /* release resource */}) 
.take(10).runLog.unsafeRun()