Imagine the following Kotlin code snippet that executes some database query using a JDBC connector:
var results : ResultSet preparedStatement.clearParameters() preparedStatement.setInt(1,value1); preparedStatement.setInt(2,value2) results = preparedStatement.executeQuery() while(results.next()) {
which compiles without problems. However, when I try to add thread safety to access to a prepared declaration:
var results : ResultSet synchronized(preparedStatement) { preparedStatement.clearParameters() preparedStatement.setInt(1,value1); preparedStatement.setInt(2,value2) results = preparedStatement.executeQuery() } while(results.next()) {
... I got the result βVariable, which should be initialized.β It seems that the synchronized block acts as a conditional block, but you can be sure that it will be executed once, before the while block.
I implemented the same block in Java and I did not receive an error. Is this a Kotlin design / implementation bug? Or does it have a good reason to act like that?
Mario source share