try-with-resources fails but try works

nav*_*pai 0 java try-catch rabbitmq try-with-resources java-11

I'm trying to set up a service which listens to a RabbitMQ server and I've set up code using the RabbitMQ Sample code from Github, which includes the following try-with-resources block

try (Connection connection = factory.newConnection();
     Channel channel = connection.createChannel()) {
        // code here
}
Run Code Online (Sandbox Code Playgroud)

When I use the same code and build and run this service using java -cp myJar.jar MyService, it just starts and ends immediately (and echo $? returns 0)

However, if I replace the block with the following, then it works fine with the same command, and I'm able to start a listener to a RabbitMQ instance

try {
     Connection connection = factory.newConnection();
     Channel channel = connection.createChannel());

     // code here
}
Run Code Online (Sandbox Code Playgroud)

The same happens even when I create database connections

try (Connection connection = dataSource.getConnection()) {
    //code here
}
Run Code Online (Sandbox Code Playgroud)

fails but

try {
    Connection connection = dataSource.getConnection();
    //code here
}  
Run Code Online (Sandbox Code Playgroud)

works fine, and allows me to use the connection to make entries into the DB as well.


Why is this happening? I'm using OpenJDK 11.0.2 and this service is standalone, but the rest of the codebase is a JAX-RS driven Rest API if it helps.

rzw*_*oot 5

当块退出时,try-with-resources构造关闭资源。基本的try块代码不会关闭任何内容。那是两者之间的区别。

当您使用try-与资源,你需要实际DO与资源的东西。

如果在要打开的资源需要“长期存在”的地方编写代码,则try-with-resources不是正确的构造(尽管通常,这意味着您正在编写的类本身应该是AutoClosable的)。