Last active
December 24, 2021 10:22
-
-
Save wplong11/4778effb2230393a2b1ff1204c5fa035 to your computer and use it in GitHub Desktop.
selenium 인스턴스 풀 관리
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlinx.coroutines.sync.Semaphore | |
| import java.util.concurrent.ConcurrentLinkedQueue | |
| open class ObjectPool<T : Any>( | |
| capacity: Int, | |
| private val instanceFactory: () -> T, | |
| ) { | |
| private val semaphore = Semaphore(permits = capacity) | |
| private val queue = ConcurrentLinkedQueue<T>() | |
| suspend fun borrow(): T { | |
| semaphore.acquire() | |
| try { | |
| return queue.poll() ?: instanceFactory() | |
| } catch (e: Exception) { | |
| semaphore.release() | |
| throw e | |
| } | |
| } | |
| fun recycle(instance: T) { | |
| queue.add(instance) | |
| semaphore.release() | |
| } | |
| open fun dispose(instance: T) { | |
| semaphore.release() | |
| } | |
| } | |
| suspend inline fun <T : Any, R> ObjectPool<T>.useInstance(block: (T) -> R): R { | |
| val instance = borrow() | |
| try { | |
| return block(instance).also { | |
| recycle(instance) | |
| } | |
| } catch (e: Exception) { | |
| dispose(instance) | |
| throw e | |
| } | |
| } | |
| /////////////////////////////////////////////////////// | |
| /////////////////////////////////////////////////////// | |
| /////////////////////////////////////////////////////// | |
| import org.openqa.selenium.remote.RemoteWebDriver | |
| open class RemoteWebDriverPool( | |
| capacity: Int, | |
| instanceFactory: () -> RemoteWebDriver, | |
| ): ObjectPool<RemoteWebDriver>(capacity, instanceFactory) { | |
| override fun dispose(instance: RemoteWebDriver) { | |
| instance.close() | |
| super.dispose(instance) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment