Skip to content
This repository was archived by the owner on Jan 6, 2023. It is now read-only.

Commit f135e41

Browse files
committed
Add awaitShutdown utils
1 parent f4a1938 commit f135e41

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package de.debuglevel.microservices.utils.spark
2+
3+
import de.debuglevel.microservices.utils.configuration.MicroserviceConfiguration
4+
import spark.Service
5+
import spark.Spark
6+
import java.io.IOException
7+
import java.net.ServerSocket
8+
9+
object SparkTestUtils {
10+
/**
11+
* Shutdown spark server and wait until Spark is finally shut down.
12+
*
13+
* This is actually a rather nasty workaround to close Spark after test and ensure that it's down when we exit this method (the actual stopping is done in a separate Thread; so we have no notification about that).
14+
* But even this does not necessarily catch all race conditions.
15+
*/
16+
fun awaitShutdown() {
17+
Spark.stop()
18+
19+
while (isLocalPortInUse(MicroserviceConfiguration.port)) {
20+
Thread.sleep(100)
21+
}
22+
23+
while (isSparkInitialized()) {
24+
Thread.sleep(100)
25+
}
26+
}
27+
28+
/**
29+
* Access the internals of Spark to check if the "initialized" flag is already set to false.
30+
*/
31+
private fun isSparkInitialized(): Boolean {
32+
33+
val sparkClass = Spark::class.java
34+
val getInstanceMethod = sparkClass.getDeclaredMethod("getInstance")
35+
getInstanceMethod.isAccessible = true
36+
val service = getInstanceMethod.invoke(null) as Service
37+
38+
val serviceClass = service::class.java
39+
val initializedField = serviceClass.getDeclaredField("initialized")
40+
initializedField.isAccessible = true
41+
val initialized = initializedField.getBoolean(service)
42+
43+
return initialized
44+
}
45+
46+
/**
47+
* Check if the Spark port could again be opened; if not, it is still in use by Spark.
48+
*/
49+
private fun isLocalPortInUse(port: Int): Boolean {
50+
return try {
51+
// ServerSocket try to open a LOCAL port
52+
ServerSocket(port).close()
53+
// local port can be opened, it's available
54+
false
55+
} catch (e: IOException) {
56+
// local port cannot be opened, it's in use
57+
true
58+
}
59+
}
60+
}

0 commit comments

Comments
 (0)