Results 1 to 12 of 12
  1. #1
    Join Date
    May 2013
    Posts
    16
    Rep Power
    0

    Default Issue with Scanner Class and Resource Leaks

    Greetings,

    I am studying Fluid Mechanics, and as a side project, I am writing a program that will perform various Fluid calculations. I have only been programming a few months, so I don't have a lot of experience. I am having an issue with the Scanner Class in that in each of my private methods, I am getting a yellow warning in Eclipse that states:

    Resource Leak: "keyboard" is never closed.

    I have googled this warning and still do not have a great grasp on how to deal with it. It has been seemingly harmless so far, but I have encountered an issue with one of my private methods, and I bet it is related to my use of the Scanner Class.

    Here is what my Demo looks like:

    Java Code:
    import java.util.Scanner;
    public class FluidDemo 
    {
    	public static void main(String[] args)
    	{
    		
    		Scanner keyboard = new Scanner(System.in);
    		Fluid fluidDemo = new Fluid();
    		
    		int choiceNumber = 0;
    		
    		introduction();
    		while (choiceNumber != 10)
    		{
    			printMenuChoices();
    			choiceNumber = keyboard.nextInt();
    			switch (choiceNumber)
    			{
    			case 1:
    				fluidDemo.calculateDensitySIUnits();
    				break;
    			case 2:
    				fluidDemo.calculateDensityBGUnits();
    				break;
    			case 3:
    				fluidDemo.calculatePressureSIUnits();
    				break;
    			case 4:
    				fluidDemo.calculatePressureBGUnits();
    				break;
    			case 5:
    				fluidDemo.calculateSpecificWeightSIUnits();
    				break;
    			case 6:
    				fluidDemo.calculateSpecificWeightBGUnits();
    				break;
    			case 7:
    				fluidDemo.calculateSpecificGravitySIUnits();
    				break;
    			case 8:
    				fluidDemo.calculateSpecificGravityBGUnits();
    			case 9:
    				fluidDemo.calculateReynoldsNumber();
    				break;
    			case 10:
    				System.out.println("\t\t\tThank you for using this program.  Have a nice day!");
    				choiceNumber = 10;
    				break;
    				default:
    				System.out.println("\t\t\tInvalid choice.  Have a nice day!");
    				choiceNumber = 10;
    				break;
    			}
    		
    		
    		}
    	}
    	//Brief Introduction to Program
    	private static void introduction()
    	{
    		System.out.println("This program will calculate various Fluid Mechanic's" +
    	" equations for you.");
    	}
    	//Description of Menu Choices
    	private static void printMenuChoices()
    	{
    		System.out.println("\t\tThe follow equations can be calculated: \n"
    				+ "\t\t\t1) Calculate Density (SI Units).\n"
    				+ "\t\t\t2) Calculate Density (BG Units).\n"
    				+ "\t\t\t3) Calculate Pressure (SI Units).\n"
    				+ "\t\t\t4) Calculate Pressure (BG Units).\n"
    				+ "\t\t\t5) Calculate Specific Weight (SI Units).\n"
    				+ "\t\t\t6) Calculate Specific Weight (BG Units).\n"
    				+ "\t\t\t7) Calculate Specific Gravity (SI Units).\n"
    				+ "\t\t\t8) Calculate Specific Gravity (BG Units).\n"
    				+ "\t\t\t9) Calculate Reynolds Number (SI Units).\n"
    				+ "\t\t\t10) Exit the program.\n");
    		
    	}
    }

    Here is one of my private methods that is marked for resource leaking:

    Java Code:
    //Read values from user for SI Density Calculation
    	private void readInputDensitySIUnits()
    	{
    		Scanner keyboard = new Scanner(System.in);
    		System.out.println("Enter the mass of the fluid (kg): ");
    		this.mass = keyboard.nextDouble();
    		System.out.println("Enter the length (m): ");
    		this.length = keyboard.nextDouble();
    	}

    Many thanks for the help.
    Last edited by no_slip_condition; 05-25-2013 at 01:15 AM.

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Issue with Scanner Class and Resource Leaks

    As the message says you never close the Scanner so close it. Check out what methods Scanner has.

    How often is that method called? If it is called a lot then you are creating a new Scanner each time. Why not create a single object as an instance variable?

  3. #3
    Join Date
    May 2013
    Posts
    16
    Rep Power
    0

    Default Re: Issue with Scanner Class and Resource Leaks

    I have a bunch of different methods that perform various calculations. I invoke a new instance of the Scanner class each time in my methods. There are different variable types, so I feel like I have to do this - I can't just have one private instance that can do it all. I also allow the user to repeat their calculation they calculate something, so if I close the Scanner, my program crashes. I don't see any way I can close the Scanner...perhaps a private method?

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: Issue with Scanner Class and Resource Leaks

    Actually, I don't see why you can't use just one instance of scanner either. If you are expecting a double for user input, then use keyboard.nextDouble(). If you are expecting an int then use keyboard.nextInt(). This is typical use of a scanner instance.


    I believe you're also missing a break statement for case 8.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    Join Date
    May 2013
    Posts
    16
    Rep Power
    0

    Default Re: Issue with Scanner Class and Resource Leaks

    I don't understand how I could do that with multiply private and public methods. Don't they each need their own instance?

    And thank you for the break. That part of my program was actually not completed yet at the time.
    Last edited by no_slip_condition; 05-25-2013 at 04:35 AM.

  6. #6
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Issue with Scanner Class and Resource Leaks

    Quote Originally Posted by no_slip_condition View Post
    I don't understand how I could do that with multiply private and public methods. Don't they each need their own instance?
    As I said you need an instance variable which belongs to the class and all methods have access to it.
    Java Code:
    class Foo {
        private Scanner scanner = new Scanner();
    
        public void someMethod() {
            String line = scanner.nextLine();
       }
    
        public void anotherMethod() {
            String name = scanner.nextLine();
        }
    }

  7. #7
    Join Date
    May 2013
    Posts
    16
    Rep Power
    0

    Default Re: Issue with Scanner Class and Resource Leaks

    The instance variable does not need to be static, just private?

    I honestly had no idea I could even do that. I'm pretty new to programming.

    Thank you!

  8. #8
    Join Date
    May 2013
    Posts
    16
    Rep Power
    0

    Default Re: Issue with Scanner Class and Resource Leaks

    e - nm

    Fantastic! Thank you very much. Problems solved.
    Last edited by no_slip_condition; 05-25-2013 at 05:38 PM.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,786
    Rep Power
    5

    Default Re: Issue with Scanner Class and Resource Leaks

    Quote Originally Posted by no_slip_condition View Post
    The instance variable does not need to be static, just private?
    Thank you!
    First you are comparing two unrelated terms, static and private. Private indicates scope of access. Static indicates how it is accessed (plus some other traits). The variable that holds the Scanner instance may be static or it may be an instance of the enclosing class. It may also be either public, protected, private or package private (no access modifier). It all depends on how you want to grant access. My philosophy, when in doubt, make them private. Any needed access will show up at compile time. And if you are interested in learning all about Java, I recommend checking out the tutorials in my signature. It covers all of this and much, much more.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    allaudin's Avatar
    allaudin is offline Senior Member
    Join Date
    Apr 2013
    Posts
    271
    Rep Power
    0

    Default Re: Issue with Scanner Class and Resource Leaks

    Just write keyboard.close() in last of your readInputDensitySIUnits() function.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: Issue with Scanner Class and Resource Leaks

    Quote Originally Posted by allaudin View Post
    Just write keyboard.close() in last of your readInputDensitySIUnits() function.
    No, don't. Closing a scanner can close the underlying Stream, and you most emphatically do not want to even try to close System.in.

    allaudin, coding blindly just to get rid of an annoying (but user-configurable) IDE-generated warning or error is never good programming practice.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  12. #12
    Join Date
    May 2013
    Posts
    16
    Rep Power
    0

    Default Re: Issue with Scanner Class and Resource Leaks

    Yeah, I knew that was bad anyway. Everythings good now.

Similar Threads

  1. Replies: 0
    Last Post: 04-17-2013, 07:12 PM
  2. Need help with a Scanner issue...
    By ndsmith20 in forum New To Java
    Replies: 4
    Last Post: 12-20-2012, 06:42 AM
  3. Scanner issue
    By Imstuck in forum New To Java
    Replies: 3
    Last Post: 12-09-2012, 05:11 PM
  4. Need advice on potential memory leaks in this class
    By Redefine12 in forum AWT / Swing
    Replies: 2
    Last Post: 06-28-2012, 03:07 AM
  5. Class Scanner looping issue
    By Stev0 in forum New To Java
    Replies: 1
    Last Post: 05-25-2008, 06:53 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •