首页 \ 问答 \ 如何正确使用guava Closer(How to use guava Closer properly)

如何正确使用guava Closer(How to use guava Closer properly)

我正在努力弄清楚如何使用番石榴库中的Closer实用程序。 请参阅下面的代码。

  • 有一点是, IndexWriter在对象初始化和close()上都抛出IOException 。 因此,finally和rethrow块中的代码带有下划线。
  • 另一个问题是,为什么我必须捕获Throwable而不是其他异常类型并且我必须重新抛出错误(我更愿意在现场记录那些)

`

int getDocumentsCount() {
    Closer closer = Closer.create();
    try {
        IndexWriter iwriter = closer.register(openIndexWriter());
        return iwriter.numDocs();
    } catch (Throwable e) {
        logger.error(e, e);
        return -1;
    } finally {
        closer.close();
    }
}


IndexWriter openIndexWriter() throws IOException {
    return new IndexWriter(directory, analyzer, false,
        IndexWriter.MaxFieldLength.UNLIMITED);
}

`

非常感谢

(坚持使用Java 6)


i'm struggling to figure out how to use the Closer utility from the guava library. Please see the code below.

  • One thing is, that the IndexWriter throws an IOException on both object initialization and close(). Therefore, the code in the finally and rethrow blocks is underlined.
  • The other question is, why do i have to catch Throwable instead of other exception types and do i have to rethrow the errors (i would prefer to log those at the spot)

`

int getDocumentsCount() {
    Closer closer = Closer.create();
    try {
        IndexWriter iwriter = closer.register(openIndexWriter());
        return iwriter.numDocs();
    } catch (Throwable e) {
        logger.error(e, e);
        return -1;
    } finally {
        closer.close();
    }
}


IndexWriter openIndexWriter() throws IOException {
    return new IndexWriter(directory, analyzer, false,
        IndexWriter.MaxFieldLength.UNLIMITED);
}

`

Thanks a lot

(stuck with Java 6)


原文:https://stackoverflow.com/questions/39658005
更新时间:2020-07-04 20:07

最满意答案

番石榴自己的解释来看,你必须使用Throwable ,是的。

这是他们的示例代码段:

public void foo() throws IOException {
  Closer closer = Closer.create();
  try {
    InputStream in = closer.register(openInputStream());
    OutputStream out = closer.register(openOutputStream());
    // do stuff with in and out
  } catch (Throwable e) { // must catch Throwable
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}

请注意,它们捕获Throwable并直接从Closer实例重新抛出它。

至于为什么它是Throwable而不是,让我们说IOExceptionRuntimeException ,这是因为Closer 必须知道发生了错误,以便它可以正确地关闭资源。 一切只是妥善处理的问题。 因此,如果你没有正确地做到它可以工作,但它不能保证。

不是说,如果您的方法可以抛出MyOwnCheckedException ,例如,您必须声明它们:

} catch (Throwable t) {
  throw closer.rethrow(e, MyOwnCheckedException.class);
} finally {
  closer.close();
}

Java 7示例,用于比较:

public void foo() throws IOException {
  try (InputStream in = openInputStream();
       OutputStream out = openOutputStream();
    // do stuff with in and out
  }
}

如果将Closer示例与Java 7示例进行比较,您可以看到我仍然需要在方法签名中声明IOException


对于您的情况,这是您必须做的:

int getDocumentsCount() {
  try {
    Closer closer = Closer.create();
    try {
       IndexWriter iwriter = closer.register(openIndexWriter());
      return iwriter.numDocs();
    } catch (Throwable e) {
      closer.rethrow(e);
    } finally {
      closer.close();
    }
  } catch (IOException e) {
    logger.error(e, e);
    return -1;
  }
}

为了避免尝试金字塔,我会做以下事情:

int getDocumentsCount() {
  try {
    return doGetDocumentsCount();
  } catch (IOException e) {
    logger.error(e, e);
    return -1;
  }
}

int doGetDocumentsCount() throws IOException {
  Closer closer = Closer.create();
  try {
    IndexWriter iwriter = closer.register(openIndexWriter());
    return iwriter.numDocs();
  } catch (Throwable e) {
    closer.rethrow(e);
  } finally {
    closer.close();
  }
}

From Guava's own explanation, you have to use Throwable, yes.

Here's their example snippet:

public void foo() throws IOException {
  Closer closer = Closer.create();
  try {
    InputStream in = closer.register(openInputStream());
    OutputStream out = closer.register(openOutputStream());
    // do stuff with in and out
  } catch (Throwable e) { // must catch Throwable
    throw closer.rethrow(e);
  } finally {
    closer.close();
  }
}

Note that they catch Throwable and rethrow it directly from the Closer instance.

As to why it is Throwable and not, let's say IOException or RuntimeException, it's because the Closer must know that an error occurred so that it can close the resources properly. All is only a matter of doing things proper. So it can work if you don't do it properly, but it's not guaranteed.

Not that if your method can throw MyOwnCheckedException, for instance, you have to declare them:

} catch (Throwable t) {
  throw closer.rethrow(e, MyOwnCheckedException.class);
} finally {
  closer.close();
}

Java 7 example, for comparison:

public void foo() throws IOException {
  try (InputStream in = openInputStream();
       OutputStream out = openOutputStream();
    // do stuff with in and out
  }
}

If you compare the Closer example with the Java 7 example, you can see that I still have to declare the IOException in the method signature.


For your case, this is what you have to do:

int getDocumentsCount() {
  try {
    Closer closer = Closer.create();
    try {
       IndexWriter iwriter = closer.register(openIndexWriter());
      return iwriter.numDocs();
    } catch (Throwable e) {
      closer.rethrow(e);
    } finally {
      closer.close();
    }
  } catch (IOException e) {
    logger.error(e, e);
    return -1;
  }
}

To avoid try-pyramids, I'd do the following:

int getDocumentsCount() {
  try {
    return doGetDocumentsCount();
  } catch (IOException e) {
    logger.error(e, e);
    return -1;
  }
}

int doGetDocumentsCount() throws IOException {
  Closer closer = Closer.create();
  try {
    IndexWriter iwriter = closer.register(openIndexWriter());
    return iwriter.numDocs();
  } catch (Throwable e) {
    closer.rethrow(e);
  } finally {
    closer.close();
  }
}
2016-09-28

相关问答

更多

x / y越接近x / y速度(The closer the x/y the more x/y velocity)

你只需要一个逆(或逆平方)关系: var increment = k / distance; 要么: var increment = k / (distance * distance); 您可以根据您想要的实际值确定k ,例如,在第一种情况下,如果您希望距离为10时增加5,则可以设置k = increment * distance = 50 。 You just need an inverse (or inverse square) relationship: var increment = ...

寻找更接近的价值(finding a closer value)

function getCloser(a, b) { b = b || 15; return Math.round(a / b) * b; } function getCloser(a, b) { b = b || 15; return Math.round(a / b) * b; }

json-schema-validator NoClassDefFoundError:com / google / common / io / Closer(json-schema-validator NoClassDefFoundError: com/google/common/io/Closer)

您必须在项目中导入番石榴库。 http://www.java2s.com/Code/Jar/g/Downloadguava150rc1jar.htm You have to import guava library in your project. http://www.java2s.com/Code/Jar/g/Downloadguava150rc1jar.htm

垂直中间对齐的图像比顶部更靠近底部(Vertically middle-aligned image is closer to the bottom than the top)

元素将在需要的地方,他需要指定它 img { height: 96px; width: 120px; margin-left: calc(50% - 60px); vertical-align: middle; } <div> <img src="https://upload.wikimedia.org/wikipedia/commons/0/02/Russula_emetica_117475.jpg"> Foo </div> that the element wou ...

jQuery找到哪个父母更接近?(jQuery find which parent is closer?)

您可以列出多个元素选择器到closest函数,它只会找到其中一个最接近的元素: $('a').closest('table, ul') 例: $(document).on("click", function( event ) { $(event.target).closest("li, b").toggleClass("hilight"); }); .hilight{ background: rgba(255, 0, 0, 0.5); } <script src="https:/ ...

遗失了PNotify(Missing PNotify closer)

在阅读了Pnotify的文档后,您必须在buttons {}选项和labels内部closer 。 new PNotify({ title: 'Sucesso', text: response.message, type: 'success', styling: 'bootstrap3', buttons: { closer: true, labels: {close: "Fechar", stick: "Manter"} }, } ...

哪个数字更接近(Which number is closer)

我认为你的意思是这样的功能: function ClosestTo(const Target, Value1, Value2: Double): Double; begin if abs(Target-Value1)<abs(Target-Value2) then Result := Value1 else Result := Value2; end; 如果您使用IfThen ,您可以更简洁地编写它: function ClosestTo(const Target, Va ...

如何正确使用guava Closer(How to use guava Closer properly)

从番石榴自己的解释来看,你必须使用Throwable ,是的。 这是他们的示例代码段: public void foo() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openInputStream()); OutputStream out = closer.register(openOutputStream()); // d ...

使用guava AbstractScheduledService(Using guava AbstractScheduledService)

AbstractScheduledServiced实现Service 。 Service接口描述了生命周期方法,包括startAsync 。 ServiceState枚举文字包含有关其含义的文档。 处于NEW状态的服务(刚刚创建): 处于此状态的服务处于非活动状态。 它做的工作量极少,占用资源极少。 要使服务执行某些有用的操作,您必须将其转换为RUNNING状态 此状态下的服务正在运行。 这就是为什么你必须在它做任何事之前启动服务的原因。 我还建议不要从构造函数中调用startAsync,而是从创 ...

在Java 8中用Guava将两个列表拖入一个不可变的多图中?(Zip two lists into an immutable multimap in Java 8 with Guava?)

我认为你的程序代码已经是最优的解决方案(无论是在内存和速度方面,假设随机访问列表)。 用小的更正,以便您的代码编译,它将是: ImmutableListMultimap.Builder<Key, Value> builder = ImmutableListMultimap.builder(); for (int i = 0; i < Math.min(keys.size(), values.size()); i++) { builder.put(keys.get(i), values.get( ...

相关文章

更多

最新问答

更多
  • 如何保护Solr只允许SELECT请求给用户并禁止其他任何东西?(How to secure Solr to allow SELECT request to only users and disallow anything else?)
  • XPath表达式无效/错误TFHpple SWIFT 1.2(XPath Expression not working/incorrect TFHpple SWIFT 1.2)
  • css3 3D变换不能平滑地制作动画(css3 3D transform doesn't animate smoothly)
  • 运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?(Run-time error '91' & Outlook.Application = Object variable or With block variable not set?)
  • 慢的webservice问题(Slow webservice problem)
  • textview的不正确对齐方式(Improper alignment of a textview)
  • 在第一步“Hello World”中出现Java错误(Cannot run “Hello World” program in Eclipse)
  • 为什么十六进制地址是14个字符?(why the hex address is 14 character?)
  • 如何在Python中的不同类中使用变量?(How to use variable in different classes in Python?)
  • asp:GridView HYPERLINKFIELD - datanavigateurlformatstring中的asp代码(asp:GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring)
  • 关于adaboost算法(About adaboost algorithm)
  • 在Matlab上内置图像(Built in Images on Matlab)
  • java swing:输入键事件时焦点丢失(java swing: Focus lost on enter key event)
  • C#中的通用约束,T是相同的TSomethingElse,对吧?(Generic constraints in C#, T is the same TSomethingElse, right?)
  • 从mybatis中的光标获取数据(Fetching data from cursor in mybatis)
  • 在运行时从XML构建对象的最佳方法(Best way for building objects out of XMLs at runtime)
  • 在整个窗口中拉伸sf :: Sprite(Stretch sf::Sprite across entire window)
  • Selenium Node API Web驱动程序等待超时处理程序(Selenium Node API web driver wait timeout handler)
  • 函数使用并且是map的一部分(循环依赖?)(Function uses and is part of map (circular dependency?))
  • 是否可以在C ++ 14中使用可选模板参数创建类型元组?(Is possible to make a tuple of types with optional template parameters in C++14?)
  • PHP从窗帘后面打印/ f(PHP prints /f from behind the curtains)
  • JFrame的contentPane的LayoutManager(LayoutManager of JFrame's contentPane)
  • 用于Instagram Feed的图像滚动(Image Roll Overs for Instagram Feed)
  • 如何显示拉伸字体(双倍宽度/高度)?(How to display stretched font (double width/height)?)
  • 文件操作API在fileapi.h和stdio.h中的WP8差异?(WP8 differences between file manipulation APIs in fileapi.h and stdio.h?)
  • 保存失败后Rails没有回滚事务()(Rails not rolling back transaction after failed save())
  • jqgrid中的分页问题与数组数据(Pagination problem in jqgrid with array data)
  • 重定向时,通过其他页面上的URL调用javascript函数(Call javascript function through url on otherpage while Redirecting)
  • 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)
  • Jquerymobile按钮仅显示页面的第一个外观(Jquerymobile buttons are shown only first apperance of the page)