In version 3.1.4
of the RabbitMQ client for Java, Connection
does not implement Closeable
so you can't use try-with-resources
when creating a new connection.
You can't do this either:
ConnectionFactory connectionFactory = new ConnectionFactory();
final Connection connection;
try {
connection = connectionFactory.newConnection();
} finally {
connection.close();
}
because your program won't compile as "Variable 'connection' might not have been initialized".
You obviously can't do this either:
ConnectionFactory connectionFactory = new ConnectionFactory();
try {
final Connection connection = connectionFactory.newConnection();
} finally {
connection.close();
}
because connection
is only defined within the scope of the try
block.
If you want to make this work, you should do something like this:
ConnectionFactory connectionFactory = new ConnectionFactory();
Connection connection = null;
try {
connection = connectionFactory.newConnection();
} finally {
if (connection != null) {
connection.close();
}
}
This has 2 drawbacks:
- You can no longer declare
connection
final - In your finally clause you have to check
connection
is notnull
before callingclose()
on it.
Ideally, the language should have allowed you to:
- Declare
connection
asfinal
- Do not force you to check it is not
null
in thefinally
clause.
From my limited experience with Kotlin, you can't do this in Kotlin either.
Kotlin still has null
s.
In the example 1 there's no sense in opening connection in try block. If
newConnection
fails theconnection
variable staysnull
, so there's nothing to close in finally block. Therefore you can movenewConnection
out of try and joinconnection
declaration and assignment, making it back final (val in Kotlin).