resource leak is never closed что это

Утечка ресурсов: «in» никогда не закрывается

Почему Eclipse дает мне утечку «утечка ресурсов» в «никогда не закрывается» в следующем коде?

ОТВЕТЫ

Ответ 1

Поскольку вы не закрываете свой сканер

Ответ 2

Как говорили другие, вам нужно вызвать «закрыть» на классах ввода-вывода. Я добавлю, что это отличное место для использования блока try-finally без catch, например:

Это гарантирует, что ваш сканер всегда будет закрыт, что гарантирует правильную очистку ресурсов.

Эквивалентно, в Java 7 или более, вы можете использовать синтаксис «try-with-resources»:

Ответ 3

В документации Eclipse, вот почему эта флага задает эту конкретную проблему (emphasis):

Классы, реализующие интерфейс java.io.Closeable (начиная с JDK 1.5) и java.lang.AutoCloseable (начиная с JDK 1.7) считаются представляют внешние ресурсы, которые должны быть закрыты с использованием метода close(), когда они больше не нужны.

Компилятор Eclipse Java способен анализировать, использует ли код такой типы придерживаются этой политики.

Компилятор отметит [нарушения] как «утечка ресурсов:» поток «никогда не закрывается».

Ответ 4

Ответ 5

Вы должны close ваш сканер, когда закончите с ним:

Ответ 6

Если вы используете JDK7 или 8, вы можете использовать try-catch с ресурсами. Это автоматически закроет сканер.

Ответ 7

выше строка вызовет конструктор класса Scanner с аргументом System.in и вернет ссылку на вновь созданный объект.

Он подключен к входному потоку, который подключен к клавиатуре, поэтому теперь во время выполнения вы можете выполнить ввод пользователя для выполнения требуемой операции.

Ответ 8

Ответ 9

Ответ 10

добавление private static Scanner in; на самом деле не устраняет проблему, оно только очищает предупреждение. Создание статического сканера означает, что он остается открытым навсегда (или до тех пор, пока класс не будет разгружен, что почти «навсегда» ). Компилятор больше не предупреждает вас, так как вы сказали ему: «Держите его открытым навсегда». Но это не то, что вы действительно хотели, так как вы должны закрыть ресурсы, как только они вам больше не понадобятся.

Ответ 11

Сканер должен быть закрыт. Хорошая практика заключается в том, чтобы закрыть «Читатели», «Потоки». и подобные объекты для освобождения ресурсов и утечек памяти aovid; и сделать это в блоке finally, чтобы убедиться, что они закрыты, даже если при обработке этих объектов возникает исключение.

Ответ 12

Я исправил его, объявив в качестве частной переменной класса Scanner. Не уверен, почему это исправлено, но это то, что рекомендуется затмение.

Ответ 13

Он закроет Scanner и закроет предупреждение.

Источник

Утечка ресурсов: «in» никогда не закрывается

Почему Eclipse дает мне утечку «утечка ресурсов» в «никогда не закрывается» в следующем коде?

ОТВЕТЫ

Ответ 1

Поскольку вы не закрываете свой сканер

Ответ 2

Как говорили другие, вам нужно вызвать «закрыть» на классах ввода-вывода. Я добавлю, что это отличное место для использования блока try-finally без catch, например:

Это гарантирует, что ваш сканер всегда будет закрыт, что гарантирует правильную очистку ресурсов.

Эквивалентно, в Java 7 или более, вы можете использовать синтаксис «try-with-resources»:

Ответ 3

В документации Eclipse, вот почему эта флага задает эту конкретную проблему (emphasis):

Классы, реализующие интерфейс java.io.Closeable (начиная с JDK 1.5) и java.lang.AutoCloseable (начиная с JDK 1.7) считаются представляют внешние ресурсы, которые должны быть закрыты с использованием метода close(), когда они больше не нужны.

Компилятор Eclipse Java способен анализировать, использует ли код такой типы придерживаются этой политики.

Компилятор отметит [нарушения] как «утечка ресурсов:» поток «никогда не закрывается».

Ответ 4

Ответ 5

Вы должны close ваш сканер, когда закончите с ним:

Ответ 6

Если вы используете JDK7 или 8, вы можете использовать try-catch с ресурсами. Это автоматически закроет сканер.

Ответ 7

выше строка вызовет конструктор класса Scanner с аргументом System.in и вернет ссылку на вновь созданный объект.

Он подключен к входному потоку, который подключен к клавиатуре, поэтому теперь во время выполнения вы можете выполнить ввод пользователя для выполнения требуемой операции.

Ответ 8

Ответ 9

Ответ 10

добавление private static Scanner in; на самом деле не устраняет проблему, оно только очищает предупреждение. Создание статического сканера означает, что он остается открытым навсегда (или до тех пор, пока класс не будет разгружен, что почти «навсегда» ). Компилятор больше не предупреждает вас, так как вы сказали ему: «Держите его открытым навсегда». Но это не то, что вы действительно хотели, так как вы должны закрыть ресурсы, как только они вам больше не понадобятся.

Ответ 11

Сканер должен быть закрыт. Хорошая практика заключается в том, чтобы закрыть «Читатели», «Потоки». и подобные объекты для освобождения ресурсов и утечек памяти aovid; и сделать это в блоке finally, чтобы убедиться, что они закрыты, даже если при обработке этих объектов возникает исключение.

Ответ 12

Я исправил его, объявив в качестве частной переменной класса Scanner. Не уверен, почему это исправлено, но это то, что рекомендуется затмение.

Ответ 13

Он закроет Scanner и закроет предупреждение.

Источник

Resource leak: ‘sc’ is never closed

Program to count how many times a particular character, letter or number occur in a sentence.

However I keep getting message:

Resource leak: ‘sc’ is never closed

I am using Java and Eclipse. What should I do?

4 Answers 4

Scanner objects need to be closed after one is done using them. So, after you’re done with it you should call the following before the end of your main method

resource leak is never closed что это. Смотреть фото resource leak is never closed что это. Смотреть картинку resource leak is never closed что это. Картинка про resource leak is never closed что это. Фото resource leak is never closed что это

after your scanner work completed put: sc.close();

resource leak is never closed что это. Смотреть фото resource leak is never closed что это. Смотреть картинку resource leak is never closed что это. Картинка про resource leak is never closed что это. Фото resource leak is never closed что это

resource leak is never closed что это. Смотреть фото resource leak is never closed что это. Смотреть картинку resource leak is never closed что это. Картинка про resource leak is never closed что это. Фото resource leak is never closed что это

If you want to use the scanner globally in a class(which is the case sometimes)

resource leak is never closed что это. Смотреть фото resource leak is never closed что это. Смотреть картинку resource leak is never closed что это. Картинка про resource leak is never closed что это. Фото resource leak is never closed что это

Not the answer you’re looking for? Browse other questions tagged java memory-leaks java.util.scanner or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.22.41046

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Java — Closing Scanner and Resource Leak

I’m learning Java and working on some projects for fun. One issue that I have run in to is that when I use a Scanner object Eclipse warns me that: «Resource Leak: ‘scan’ is never closed.»

So, I added a scan.close(); at the end of my code and that takes care of the warning.

The problem comes in because I have other classes in the same package that also use scanner objects and and Eclipse tells me to close scanner in those classes respectively. However, when I do that it seems like it closes ALL of the scanner objects and I get errors during run time.

Here is an example of what causes the error:

After scanner is closed in the scanTest class and the do loop in test2 is entered again an error occurs at the line test = scan.nextInt();

I tried moving the creation of the scanner object into the do loop just to make a new object every time as well but the error still occurs.

Not sure why this is happening or how I can make sure all my I/O objects are closed out without running into problems.

One post I came across mentioned that when System.in is closed I cannot be re-opened. If this is the case would I just need to make sure a scanner object with System.in is closed at the very end of the program and @suppress all of the other scanner warnings in other classes? Or would that still leave all those scanner objects open (bad)? Or should I make a global scanner variable and then close it at the very end of my program (but some teachers have told me using global variables is frowned upon)?

Any advice would be appreciated. Thanks for helping me learn!

Источник

Resource leak warning when using Scanner [duplicate]

I’m watching some java tutorials and wondering about the resource leak warning when using Scanner.

I know I can close it, but the person in the video is not getting a warning even though he is using the exact same code, why is that?

1 Answer 1

The actual problem

It’s.. complicated. The general rule is that whomever makes the resource must also safely close it, and because your code makes a Scanner, the IDE is telling you: Hey, you should close that.

The problem is, the IDE can’t really know this. The underlying problem is that System.in is extremely badly designed API in many many ways, but [A] it’s 30 years old, back then it was a lot harder to know that; we know it now because of hindsight, and [B] oracle hasn’t gotten around to making a second version of the sysin/out/err API yet, and it’s not high on the agenda.

This leaves IDEs in trouble: It’s relatively easy to set up some patterns and rules for using resources such that you never have any problems with this ‘filters you created that wrap around resources you did not create’, but you can’t use them with sysin/err/out without writing a little framework, and that’s a bit much to ask for newbies. It’s also not a good idea presumably to tell those taking their first steps in java coding to first go download some third party library that cleans up sysin/out/err interaction a bit.

Thus, we’re in limbo. IDEs should NOT warn about this, but it’s hard for them to detect that this is an exotic sccenario where you have a resource you made that you nevertheless don’t need to close, and in fact, should not close.

You can turn off the setting for ‘unclosed resources’, which no doubt the video tutorial did, but it is a useful warning. Just.. hampered by this silly old API that makes no sense anymore.

Some in-depth explanation

You can split the world of all WRIOs into:

The rules on closing them boil down to:

The problem with filters

If it’s a filter provided to you with the intent that you close it:

then failure to close br is a resource leak; IDE warnings are warranted.

If it’s a filter you made, wrapping around a WRIO you also made:

Then, there is the problem case:

Making a filter WRIO that wraps around a resource you did not make and do not have the responsibility to close: You should actively NOT be closing these filter WRIOs, as that will end up closing the underlying resource and you did not want that.

Here an IDE warning is actively bad and annoying, but it is very hard for an IDE to realize this.

The design solution

Normally, you fix this by never getting in that scenario. For example, System.in should have better API; this API would look like:

and have the property that closing s does not close System.in itself (it would do mostly nothing; set a boolean flag to throw exceptions if any further read calls are done, or possibly even do literally nothing). Now the IDE warning is at best overzealous, but heeding its advice and safely closing your scanner is now no longer actively introducing bugs in your code.

Unfortunately, that nice API doesn’t exist (yet?). Thus we’re stuck with this annoying scenario where a useful IDE warning system actively misleads you because of bad API design. If you really want to, you could write it:

Now you can heed those warnings by following its advice:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *