29

我正在创作一个 java 库。一些打算供图书馆用户使用的类拥有本地系统资源(通过 JNI)。我想确保用户“处置”这些对象,因为它们很重,并且在测试套件中它们可能会导致测试用例之间的泄漏(例如,我需要确保TearDown将处置)。为此,我让 Java 类实现了 AutoCloseable,但这似乎还不够,或者我没有正确使用它:

  1. 我看不到如何try-with-resources在测试上下文中使用语句(我正在使用JUnit5with Mockito),因为“资源”不是短暂的 - 它是测试夹具的一部分。

  2. 一如既往地勤奋,我尝试finalize()在那里实现和测试闭包,但结果finalize()甚至没有被称为(Java10)。这也被标记为已弃用,我相信这个想法会不受欢迎。

这是怎么做到的?需要明确的是,如果应用程序的测试(使用我的库)不调用close()我的对象,我希望它们失败。


编辑:如果有帮助,请添加一些代码。这并不多,但这是我正在尝试做的。

@SuppressWarnings("deprecation") // finalize() provided just to assert closure (deprecated starting Java 9)
@Override
protected final void finalize() throws Throwable {
    if (nativeHandle_ != 0) {
         // TODO finalizer is never called, how to assert that close() gets called?
        throw new AssertionError("close() was not called; native object leaking");
    }
}

Edit2, 赏金结果谢谢大家的回复,一半的赏金是自动奖励的。我得出结论,对于我的情况,最好尝试涉及Cleaner. 然而看起来,清洁动作虽然已注册,但并未被调用。我在这里问了一个后续问题。

4

5 回答 5

17

这篇文章不直接回答你的问题,但提供了不同的观点。

让您的客户持续致电的一种方法close是将他们从这种责任中解放出来。

你怎么能这样做?

使用模板模式。

草图实现

您提到您正在使用 TCP,所以让我们假设您有一个TcpConnection具有close()方法的类。

让我们定义TcpConnectionOperations接口:

public interface TcpConnectionOperations {
  <T> T doWithConnection(TcpConnectionAction<T> action);
}

并实施它:

public class TcpConnectionTemplate implements TcpConnectionOperations {
  @Override
  public <T> T doWithConnection(TcpConnectionAction<T> action) {
    try (TcpConnection tcpConnection = getConnection()) {
      return action.doWithConnection(tcpConnection);
    }
  }
}

TcpConnectionAction只是一个回调,没什么花哨的。

public interface TcpConnectionAction<T> {
  T doWithConnection(TcpConnection tcpConnection);
}

图书馆现在应该怎么消费?

  • 只能通过TcpConnectionOperations接口消费。
  • 消费者提供行动

例如:

String s = tcpConnectionOperations.doWithConnection(connection -> {
  // do what we with with the connection
  // returning to string for example
  return connection.toString();
});

优点

  • 客户不必担心:
    • 得到一个TcpConnection
    • 关闭连接
  • 您可以控制创建连接:
    • 你可以缓存它们
    • 记录他们
    • 收集统计数据
    • 许多其他用例...
  • 在测试中,您可以提供模拟TcpConnectionOperations和模拟TcpConnections并对它们进行断言

缺点

如果资源的生命周期长于action. 例如,客户端有必要将资源保留更长时间。

然后,您可能想深入了解ReferenceQueue/ Cleaner(从 Java 9 开始)和相关 API。

灵感来自 Spring 框架

这种模式在Spring 框架中被广泛使用。

参见例如:

2/7/19 更新

如何缓存/重用资源?

这是某种化:

池是随时可用的资源集合,而不是在使用时获取并释放

Java中的一些池:

在实施池时,提出了几个问题:

  • 什么时候资源实际上应该是closed?
  • 资源应该如何在多个线程之间共享?

什么时候资源应该是closed?

通常池提供一个显式close方法(它可能有不同的名称,但目的是相同的),它关闭所有持有的资源。

它如何跨多个线程共享?

它取决于一种资源本身。

通常你想确保只有一个线程访问一个资源。

这可以使用某种锁定来完成

演示

请注意,此处提供的代码仅用于演示目的它具有糟糕的性能并且违反了一些 OOP 原则。

IpAndPort.java

@Value
public class IpAndPort {
  InetAddress address;
  int port;
}

TcpConnection.java

@Data
public class TcpConnection {
  private static final AtomicLong counter = new AtomicLong();

  private final IpAndPort ipAndPort;
  private final long instance = counter.incrementAndGet();

  public void close() {
    System.out.println("Closed " + this);
  }
}

CachingTcpConnectionTemplate.java

public class CachingTcpConnectionTemplate implements TcpConnectionOperations {
  private final Map<IpAndPort, TcpConnection> cache
      = new HashMap<>();
  private boolean closed; 
  public CachingTcpConnectionTemplate() {
    System.out.println("Created new template");
  }

  @Override
  public synchronized <T> T doWithConnectionTo(IpAndPort ipAndPort, TcpConnectionAction<T> action) {
    if (closed) {
      throw new IllegalStateException("Closed");
    }
    TcpConnection tcpConnection = cache.computeIfAbsent(ipAndPort, this::getConnection);
    try {
      System.out.println("Executing action with connection " + tcpConnection);
      return action.doWithConnection(tcpConnection);
    } finally {
      System.out.println("Returned connection " + tcpConnection);
    }
  }

  private TcpConnection getConnection(IpAndPort ipAndPort) {
    return new TcpConnection(ipAndPort);
  }


  @Override
  public synchronized void close() {
    if (closed) {
      throw new IllegalStateException("closed");
    }
    closed = true;
    for (Map.Entry<IpAndPort, TcpConnection> entry : cache.entrySet()) {
      entry.getValue().close();
    }
    System.out.println("Template closed");
  }
}
测试基础设施

TcpConnectionOperationsParameterResolver.java

public class TcpConnectionOperationsParameterResolver implements ParameterResolver, AfterAllCallback {
  private final CachingTcpConnectionTemplate tcpConnectionTemplate = new CachingTcpConnectionTemplate();

  @Override
  public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    return parameterContext.getParameter().getType().isAssignableFrom(CachingTcpConnectionTemplate.class)
        && parameterContext.isAnnotated(ReuseTemplate.class);
  }

  @Override
  public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
    return tcpConnectionTemplate;
  }

  @Override
  public void afterAll(ExtensionContext context) throws Exception {
    tcpConnectionTemplate.close();
  }
}

和来自 JUnit ParameterResolverAfterAllCallback

@ReuseTemplate是自定义注解

ReuseTemplate.java

@Retention(RetentionPolicy.RUNTIME)
public @interface ReuseTemplate {
}

最后测试:

@ExtendWith(TcpConnectionOperationsParameterResolver.class)
public class Tests2 {
  private final TcpConnectionOperations tcpConnectionOperations;

  public Tests2(@ReuseTemplate TcpConnectionOperations tcpConnectionOperations) {
    this.tcpConnectionOperations = tcpConnectionOperations;
  }

  @Test
  void google80() throws UnknownHostException {
    tcpConnectionOperations.doWithConnectionTo(new IpAndPort(InetAddress.getByName("google.com"), 80), tcpConnection -> {
      System.out.println("Using " + tcpConnection);
      return tcpConnection.toString();
    });
  }

  @Test
  void google80_2() throws Exception {
    tcpConnectionOperations.doWithConnectionTo(new IpAndPort(InetAddress.getByName("google.com"), 80), tcpConnection -> {
      System.out.println("Using " + tcpConnection);
      return tcpConnection.toString();
    });
  }

  @Test
  void google443() throws Exception {
    tcpConnectionOperations.doWithConnectionTo(new IpAndPort(InetAddress.getByName("google.com"), 443), tcpConnection -> {
      System.out.println("Using " + tcpConnection);
      return tcpConnection.toString();
    });
  }
}

跑步:

$ mvn test

输出:

Created new template
[INFO] Running Tests2
Executing action with connection TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Using TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Returned connection TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Executing action with connection TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=443), instance=2)
Using TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=443), instance=2)
Returned connection TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=443), instance=2)
Executing action with connection TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Using TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Returned connection TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Closed TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=80), instance=1)
Closed TcpConnection(ipAndPort=IpAndPort(address=google.com/74.125.131.102, port=443), instance=2)
Template closed

这里的关键观察是连接被重用(参见“ instance=”)

这是可以做什么的过于简单的例子。当然,在现实世界中,池连接并不是那么简单。池不应该无限增长,连接只能保持特定的时间段等等。通常一些问题可以通过在后台添加一些东西来解决。

回到问题

我看不到如何try-with-resources statement在测试上下文中使用(我正在使用JUnit5with Mockito),因为“资源”不是短暂的 - 它是测试夹具的一部分。

请参阅Junit 5 用户指南。扩展模型

一如既往地勤奋,我尝试finalize()在那里实现和测试闭包,但结果finalize()甚至没有被称为(Java10)。这也被标记为已弃用,我相信这个想法会不受欢迎。

您覆盖finalize了它以引发异常,但它们被忽略了。

Object#finalize

如果 finalize 方法抛出未捕获的异常,则忽略该异常并终止该对象的终结。

您可以在这里做的最好的事情是记录资源泄漏和close资源

需要明确的是,如果应用程序的测试(使用我的库)不调用close()我的对象,我希望它们失败。

应用程序测试如何使用您的资源?他们是否使用new运算符对其进行实例化?如果是,那么我认为PowerMock可以帮助您(但我不确定)

如果您在某种工厂背后隐藏了资源的实例化,那么您可以为应用程序测试一些模拟工厂


有兴趣的可以看这个讲座。它是俄语的,但仍然可能会有所帮助(我的部分答案基于此演讲)。

于 2019-02-01T12:01:33.000 回答
6

如果我是你,我会做以下事情:

  • 围绕返回“重”对象的调用编写一个静态包装器
  • 创建一个PhantomReferences集合来容纳所有重物,用于清理目的
  • 创建一个WeakReferences集合来保存所有重对象,以检查它们是否被 GC 处理(是否有来自调用者的任何引用)
  • 在拆解时,我会检查包装器以查看哪些资源已被 GC(在 Phantom 中有引用,但在 Weak 中没有),我会检查它们是否已关闭或不正确。
  • 如果在提供资源时添加一些调试/调用者/堆栈跟踪信息,将更容易追溯泄漏的测试用例。

这还取决于您是否想在生产环境中使用这种机制——也许值得将此功能添加到您的库中,因为资源管理在生产环境中也是一个问题。在这种情况下,您不需要包装器,但您可以使用此功能扩展您当前的类。您可以使用后台线程进行定期检查,而不是拆卸。

关于参考类型,我推荐这个链接。建议将 PhantomReferences 用于资源清理。

于 2019-02-01T10:19:06.903 回答
1

一般来说,如果您可以可靠地测试资源是否已关闭,您可以自己关闭它。

首先要做的是让客户端更容易处理资源。使用 Execute Around 成语。

据我所知,在 Java 库中执行资源处理的唯一用途是java.security.AccessController.doPrivileged,这很特别(资源是一个神奇的堆栈框架,你真的不想让它保持打开状态)。我相信 Spring 长期以来一直为此提供急需的 JDBC 库。在 Java 1.1 模糊实用后不久,我肯定在使用 JDBC 执行(当时不知道它被称为)。

库代码应类似于:

@FunctionalInterface
public interface WithMyResource<R> {
    R use(MyResource resource) throws MyException;
}
public class MyContext {
// ...
    public <R> R doAction(Arg arg, WithMyResource<R> with) throws MyException {
        try (MyResource resource = acquire(arg)) {
            return with.use(resource);
        }
    }

(务必在正确的位置获取类型参数声明。)

客户端使用如下所示:

MyType myResult = yourContext.doContext(resource -> {
    ...blah...;
    return ...thing...;
});

回到测试。即使被测试者从执行环境中窃取了资源或者其他一些可用的机制,我们如何使测试变得容易?

显而易见的答案是您为测试提供了执行周围的解决方案。您将需要提供一些执行周围使用 API 来验证您在范围内获取的所有资源也已关闭。这应该与获取资源的上下文配对,而不是使用全局状态。

根据您的客户使用的测试框架,您可能能够提供更好的东西。例如,JUnit5 有一个基于注释的扩展工具,它允许您提供上下文作为参数,并在每个测试执行后应用检查。(不过我用的不多,就不多说了。)

于 2019-02-07T10:44:30.027 回答
1

如果您对测试的一致性感兴趣,只需将注释destroy()标记的方法添加@AfterClass到测试类中并关闭其中所有先前分配的资源。

如果您对允许您保护资源不被关闭的方法感兴趣,您可以提供一种不向用户显式公开资源的方法。例如,您的代码可以控制资源生命周期并仅接受Consumer<T>用户。

如果你不能这样做,但仍然想确保即使用户没有正确使用资源也会关闭它,你将不得不做一些棘手的事情。sharedPtr您可以拆分您的资源resource本身。然后暴露sharedPtr给用户并将其放入包裹在WeakReference. 因此,您将能够捕捉到 GC 删除并sharedPtr调用close(). resource请注意,resource不得暴露给用户。我准备了一个例子,它不是很准确,但希望它能说明这个想法:

public interface Resource extends AutoCloseable {

    public int jniCall();
}
class InternalResource implements Resource {

    public InternalResource() {
        // Allocate resources here.
        System.out.println("Resources were allocated");
    }

    @Override public int jniCall() {
        return 42;
    }

    @Override public void close() {
        // Dispose resources here.
        System.out.println("Resources were disposed");
    }
}
class SharedPtr implements Resource {

    private final Resource delegate;

    public SharedPtr(Resource delegate) {
        this.delegate = delegate;
    }

    @Override public int jniCall() {
        return delegate.jniCall();
    }

    @Override public void close() throws Exception {
        delegate.close();
    }
}
public class ResourceFactory {

    public static Resource getResource() {
        InternalResource resource = new InternalResource();
        SharedPtr sharedPtr = new SharedPtr(resource);

        Thread watcher = getWatcherThread(new WeakReference<>(sharedPtr), resource);
        watcher.setDaemon(true);
        watcher.start();

        Runtime.getRuntime().addShutdownHook(new Thread(resource::close));

        return sharedPtr;
    }

    private static Thread getWatcherThread(WeakReference<SharedPtr> ref, InternalResource resource) {
        return new Thread(() -> {
            while (!Thread.currentThread().isInterrupted() && ref.get() != null)
                LockSupport.parkNanos(1_000_000);

            resource.close();
        });
    }
}
于 2019-02-01T09:06:48.803 回答
0

Factory methods我将通过我可以控制它们的创建来为这些对象提供实例,并且我将为消费者提供关闭对象Proxies的逻辑

interface Service<T> {
 T execute();
 void close();
}

class HeavyObject implements Service<SomeObject> {
  SomeObject execute() {
  // .. some logic here
  }
  private HeavyObject() {}

  public static HeavyObject create() {
   return new HeavyObjectProxy(new HeavyObject());
  }

  public void close() {
   // .. the closing logic here
  }
}

class HeavyObjectProxy extends HeavyObject {

  public SomeObject execute() {
    SomeObject value = super.execute();
    super.close();
    return value;
  }
}
于 2019-02-01T19:06:09.753 回答