Page 1 of 4 123 ... LastLast
Results 1 to 20 of 68

Thread: Threads!!!

  1. #1
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Threads!!!

    To the forum,

    I am trying to implement threads into an existing program, and my program keeps hanging making me suspect that I am not synchronizing the methods or data correctly, but I just don't know where to start looking for this? Can anyone help by showing me how to see into what the code is doing when it hangs? This is an ATM.java program, Server.java output below:

    Accepting clients now
    Client acquired on port #7777, reading from socket

    When I run the Client.java program I get the following:

    ATMProxy writing command to server: BALANCE
    Server returned: 10.0
    Balance: 10.0
    Depositing: 1000
    ATMProxy writing command to server: DEPOSIT
    ATMProxy writing command to server: BALANCE
    Server returned: 10.0
    Balance: 10.0
    Withdrawing: 250
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    Server returned: 10.0
    Balance: 10.0
    Withdrawing: 750
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    Server returned: 10.0
    Balance: 10.0


    The issue as you can see is that Server.java never ends as it should, it is kind of in a race condition (since my CPU goes nuts) I think...but Client seems to work, but it does not return the proper BALANCE after the Deposit and the Withdrawal...

    I am lost...

    thanks

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    my program keeps hanging
    Do you know where it is hanging?

    There is not enough info in your post to make any suggestions about what your problem is.

  3. #3
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Below is the Server.java program running, and I put println statements. The first part of Server is just getting the commands from the Client.java program which you see as BALANCE, DEPOSIT, and WITHDRAWAL. You notice that BALANCE Works evidenced by the Client.java output at the bottom of this message, since I preloaded 10,000 into the account, and as I change the account value, the program spits out the correct one each time. The issue is that the program is supposed to DEPOSIT and WITHDRAW the balances associated, but that never happens per the output on the client side, as it stays at 10,000...

    So based on the below output, it looks like i am in a program called ATMRunnable.java (implements Runnable) that contains my run() method. It appears to be going through this repeatedly, since the output of "Here I am!!!Threads should go here eventually..." is within this program..

    I can post the code if you feel that is appropriate...

    huit-smartino:Desktop spm888$ java cscie160/hw6/Server 7777
    Accepting clients now
    Client acquired on port #7777, reading from socket
    requestQueue Size is: 1
    commandLine equals: BALANCE
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    Here I am!!!Threads should go here eventually...
    requestQueue Size is: 1
    commandLine equals: DEPOSIT 1000.0
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    requestQueue Size is: 1
    commandLine equals: BALANCE
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    Here I am!!!Threads should go here eventually...
    requestQueue Size is: 1
    commandLine equals: WITHDRAW 250.0
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    Here I am!!!Threads should go here eventually...
    requestQueue Size is: 1
    commandLine equals: BALANCE
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    Here I am!!!Threads should go here eventually...
    requestQueue Size is: 1
    commandLine equals: WITHDRAW 750.0
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    Here I am!!!Threads should go here eventually...
    requestQueue Size is: 1
    commandLine equals: BALANCE
    requestQueue Size is: 1
    requestQueue Size is: 1
    I am returning atmRunnableItem!!!
    Here I am!!!Threads should go here eventually...
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream. java:168)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.j ava:264)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.ja va:306)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:1 58)
    at java.io.InputStreamReader.read(InputStreamReader.j ava:167)
    at java.io.BufferedReader.fill(BufferedReader.java:13 6)
    at java.io.BufferedReader.readLine(BufferedReader.jav a:299)
    at java.io.BufferedReader.readLine(BufferedReader.jav a:362)
    at cscie160.hw6.Server.serviceClient(Server.java:47)
    at cscie160.hw6.Server.main(Server.java:87)
    Here I am!!!Threads should go here eventually...


    =========Output from Client.java============


    HUIT-SMartino:Desktop spm888$ java cscie160/hw6/Client localhost 7777
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    Depositing: 1000
    ATMProxy writing command to server: DEPOSIT
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    Withdrawing: 250
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    Withdrawing: 750
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    HUIT-SMartino:Desktop spm888$ java cscie160/hw6/Client localhost 7777
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    Depositing: 1000
    ATMProxy writing command to server: DEPOSIT
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    Withdrawing: 250
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0
    Withdrawing: 750
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    Server returned: 10000.0
    Balance: 10000.0

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    Your print out do not explain what the code is doing. The trace shows that serviceClient was doing a readLine() call when it happened.
    Only code will show what we need to know to solve the problem.
    Can you make a SSCCE to demonstrate what the code does and that shows the problem?

  5. #5
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Sorry, but what is a SSCCE? NewToJava...

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    When I type that into Google I get:
    Describes the short, self contained, correct example. A useful technique for debugging.

    Something that we can take home to work on.

  7. #7
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Not sure that I can do that any better than what I have now...can I send a .jar file to you directly?

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    No, post the code here on the forum so anyone can help.

  9. #9
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Here is Server.java==========================

    Java Code:
    package cscie160.hw6;
    
    import java.net.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.*;
    
    /** The intent of the Java program (Server.java) is to simulate an ATM server listening for requests from Client ATM machines.  The Server accepts the commands from Client->ATMProxy of BALANCE, DEPOSIT, or WITHDRAW.  It then calls ATMImplementation.java which in turns establishes the initial accountBalance of 0 and either adds (DEPOSIT) or subtracts (WITHDRAWS) from the accountBalance within ATMImplementation.java  Server establishes a socket on the port supplied by the argument when executed.  I uses 7777 in my examples, i.e.:  java cscie160/hw4/Server 7777
    */
    
    
    public class Server 
    {
        private ServerSocket serverSocket;
        private ATMImplementation atmImplementation = new ATMImplementation();	
        private BufferedReader bufferedReader;
        List<ATMRunnable> requestQueue;
        ATMThread[] atmthread = new ATMThread[5];
        public Server(int port) throws java.io.IOException, InterruptedException 
    	{
    		serverSocket = new ServerSocket(port);
                    atmImplementation = new ATMImplementation();
                    requestQueue = new ArrayList<ATMRunnable>();
    
        }
    
    	
        /** serviceClient accepts a client connection and reads lines from the socket.
         *  Each line is handed to executeCommand for parsing and execution.
         */
        public void serviceClient(ATMImplementation atmImplementation) throws java.io.IOException, InterruptedException
    	{
    		System.out.println("Accepting clients now");
    		Socket clientConnection = serverSocket.accept();
    		
    		// Arrange to read input from the Socket	
    		InputStream inputStream = clientConnection.getInputStream();
    		bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    		
    		// Arrange to write result across Socket back to client
    		OutputStream outputStream = clientConnection.getOutputStream();
                    PrintStream printStream = new PrintStream(outputStream);
    		
    		System.out.println("Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket");
    		
    			String commandLine;
    			while ((commandLine = bufferedReader.readLine()) != null) 
    			{
    				try 
    				{
                                      ATMRunnable atmRunnable = new ATMRunnable(commandLine, outputStream, atmImplementation);
                                      requestQueue.add(atmRunnable);
                                      System.out.println("requestQueue Size is: " + requestQueue.size());
                                      System.out.println("commandLine equals: " + commandLine);
    
    				} catch (Exception atmex) 
    				{
    					System.out.println("ERROR: " + atmex);
    				} 
    		                     ATMThread Thread1 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread2 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread3 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread4 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread5 = new ATMThread(requestQueue);		
                           }
    	}
    	
    	public static void main(String argv[]) 
    	{
    
    
    		int port = 1099;
    		if(argv.length > 0) 
    		{
    			try 
    			{
    				port = Integer.parseInt(argv[0]);
    			} 
    			catch (Exception e) 
    			{ 
    				e.printStackTrace(); 
    			}
    		}
    		try 
    		{
    			Server server = new Server(port);
    			server.serviceClient(server.atmImplementation);
    			System.out.println("Client serviced");
    		} 
    		catch (Exception ex) 
    		{
    			ex.printStackTrace();
    		}
    	}
    private final int MAX_THREADS = 5;
    }
    Here is Client.java==============================

    Java Code:
    package cscie160.hw6;
    
    /** Client.java calls ATMProxy methods getBalance(), deposit(), and withdraw(), but first performing a getBalance (retrieve current balance) from Server (which in turn calls ATMImplementation.java) for current accountBalance.  Next this program calls atm.deposit with a 1000 deposit which is a DEPOSIT to Server.java, thus adding to the accountBalance in ATMImplementation.java.  Finally a withdrawal is made of $250 which is a WITHDRAWAL to Server.java, thus subtracting from the accountBalance in ATMImplementation.java.  Client takes the arguments of localhost for the network, and a port to listen on (I use 7777) in my examples.
    */
    
    public class Client 
    {
        public static void main(String[] args) 
    	{
    		try 
    		{
                // parse command line arguments
                String host = args[0];
                int port = Integer.parseInt(args[1]);
                ATM atm = new ATMProxy(host, port);
                // get initial account balance
                System.out.println("Balance: "+atm.getBalance());
                // make $1000 deposit and get new balance    
                System.out.println(" Depositing: 1000");
                atm.deposit(1000);
                System.out.println("Balance: "+atm.getBalance());
                // make $250 withdrawal and get new balance
                System.out.println(" Withdrawing: 250");
                atm.withdraw(250);
                System.out.println("Balance: "+atm.getBalance());
                // make $750 withdrawal and get new balance
                System.out.println(" Withdrawing: 750");
                atm.withdraw(750);
                System.out.println("Balance: "+atm.getBalance());
    		} 
    		catch (Exception ae) 
    		{
                System.out.println("An exception occurred while communicating with the ATM");
                ae.printStackTrace();
    		}
        }
    }
    
    
    Here is ATMThread.java=====================================
    
    
    package cscie160.hw6;
    
    import java.util.StringTokenizer; 
    import java.io.*; 
    import java.net.*; 
    import java.util.*; 
    
    public class ATMThread 
    { 
    
    Thread threadedApplication; 
    
    public ATMThread(List<ATMRunnable> requestQueue) throws InterruptedException 
    { 
    
    threadedApplication = new Thread(iterateThroughTherequestQueue(requestQueue)); 
    threadedApplication.start(); 
    
    } 
    
    
    public synchronized ATMRunnable iterateThroughTherequestQueue(List<ATMRunnable> requestQueue) throws InterruptedException
      { 
    
        ATMRunnable atmRunnableItem=null; 
    
        while(requestQueue.isEmpty()) 
               {
    
                 try
                   {
                    requestQueue.wait(); 
    
                   } catch (InterruptedException e) {
                       e.printStackTrace(); 
                   } 
               } 
    
             int requestQueueSz = requestQueue.size(); //size of the collection
                 System.out.println("requestQueue Size is: " + requestQueueSz);
             int o = 0;
    
             for(int i=0; i < requestQueueSz; i++)
                {
                 synchronized (this) {
                 atmRunnableItem = requestQueue.get(o);
                 requestQueue.remove(o); 
                 System.out.println("requestQueue Size is: " + requestQueueSz);
                 }
                }
    
            System.out.println("I am returning atmRunnableItem!!!");
    
            return atmRunnableItem; 
      } 
    } 
    
    
    Here is ATMRunnable.java===================
    
    
    package cscie160.hw6;
    
    import java.net.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.*;
    
    /** The intent of the Java program (Server.java) is to simulate an ATM server listening for requests from Client ATM machines.  The Server accepts the commands from Client->ATMProxy of BALANCE, DEPOSIT, or WITHDRAW.  It then calls ATMImplementation.java which in turns establishes the initial accountBalance of 0 and either adds (DEPOSIT) or subtracts (WITHDRAWS) from the accountBalance within ATMImplementation.java  Server establishes a socket on the port supplied by the argument when executed.  I uses 7777 in my examples, i.e.:  java cscie160/hw4/Server 7777
    */
    
    public class ATMRunnable implements Runnable
    {
        private ServerSocket serverSocket;
        Socket clientConnection;
        private ATMImplementation atmImplementation = new ATMImplementation();	
        private BufferedReader bufferedReader;
        private String commandLine;
        private OutputStream outputStream;
        private PrintStream printStream;
    
        public ATMRunnable (String commandLine, OutputStream outputStream, ATMImplementation atmImplementation) throws java.io.IOException 
    	{
             synchronized (this) {
             this.commandLine = commandLine;
             this.atmImplementation = atmImplementation;
             this.outputStream = outputStream;
           }
            }
    	
        /** serviceClient accepts a client connection and reads lines from the socket.
         *  Each line is handed to executeCommand for parsing and execution.
         */
        
        public String getCommandLine()
         {
    
           return commandLine;
         }
    
        public synchronized void run() 
    	{
    		System.out.println("Here I am!!!Threads should go here eventually...");
    		//System.out.println("this.commandLine = " + this.commandLine);
                    PrintStream printStream = new PrintStream(outputStream);
    		
    			while (this.commandLine != null) 
    			{
    				try 
    				{
    					Float result = executeCommand(this.commandLine);
    					// Only BALANCE command returns non-null
    					if (result != null) 
    					{ 
    						printStream.println(result);  // Write it back to the client
    					}
    				} 
    				catch (ATMException atmex) 
    				{
    					System.out.println("ERROR: " + atmex);
    				} 
    				
    			}
    		}
    	
    	/** The logic here is specific to our protocol.  We parse the string
    	 *  according to that protocol.
    	 */
    	private Float executeCommand(String commandLine) throws ATMException 
    	{
    		// Break out the command line into String[]
    		StringTokenizer tokenizer = new StringTokenizer(commandLine);
    		String commandAndParam[] = new String[tokenizer.countTokens()];
    		int index = 0;
    		while (tokenizer.hasMoreTokens()) 
    		{
    			commandAndParam[index++] = tokenizer.nextToken();
    		}
    		String command = commandAndParam[0];
    		// Dispatch BALANCE request without further ado.
    		if (command.equalsIgnoreCase(Commands.BALANCE.toString())) 
    		{
    		 //System.out.println("I am in getBalance  = " + commandLine);
    			return this.atmImplementation.getBalance();
    		}
    		// Must have 2nd arg for amount when processing DEPOSIT/WITHDRAW commands
    		if (commandAndParam.length < 2) 
    		{
    			throw new ATMException("Missing amount for command \"" + command + "\"");
    		}
    		try 
    		{
    			float amount = Float.parseFloat(commandAndParam[1]);
    			if (command.equalsIgnoreCase(Commands.DEPOSIT.toString())) 
    			{
    		                //System.out.println("I am in DEPOSIT  = " + commandLine);
    				this.atmImplementation.deposit(amount);	      
                                    notifyAll();
    			}
    			else if (command.equalsIgnoreCase(Commands.WITHDRAW.toString())) 
    			{
    		                //System.out.println("I am in WITHDRAW  = " + commandLine);
    				this.atmImplementation.withdraw(amount);
                                    notifyAll();
    			} else 
    			{
    				throw new ATMException("Unrecognized command: " + command);
    			}
    		} 
    		catch (NumberFormatException nfe) 
    		{
    			throw new ATMException("Unable to make float from input: " + commandAndParam[1]);
    		}
    		// BALANCE command returned result above.  Other commands return null;
    		return null;
    	}
    	
    }
    
    
    Here is Account.java=================================
    
    
    package cscie160.hw6;
    
    /** The intent of this Java program (Account.java) is to simulate a single ATM or Bank account for the user.  The accountBalance begins at zero (0) and is called from ATMImplementation.java.
    */
    
    public class Account
    {
        public Account()
            {
                    accountBalance = 10000;
        }
    public float getAccountBalance() {
    return accountBalance;
    }
    private float accountBalance;
    }
    
    Here is ATM.java===========================
    
    package cscie160.hw6;
    
    public interface ATM 
    {
    	public void deposit(float amount) throws ATMException;
    	public void withdraw(float amount) throws ATMException;
    	public Float getBalance() throws ATMException;
    }
    
    Here is ATMException.java========================
    
    package cscie160.hw6;
    
    public class ATMException extends Exception 
    {
        public ATMException(String msg) 
    	{
    		super(msg);
        }
    }
    
    Here is ATMImplementation.java======================
    
    package cscie160.hw6;
    
    /** Client-side proxy class which manages the connection to the
     *  server and forwards the client's requests to the server by writing
     *  the text of requests to the stream on top of the sockect established
     *  at creation time when the constructor is called.
     */
    public class ATMImplementation implements ATM 
    {
       public ATMImplementation()
        { 
          Account account = new Account();
          balance = account.getAccountBalance();
        }
    
    public Float getBalance() 
    {
    //System.out.println("I am in ATMImplementation GETTING A BALANCE");
     return balance;
    }
    
    public void deposit(float amount)
    {
    //System.out.println("I am in ATMImplementation making a DEPOSIT");
    balance = balance + amount;
    }
    
    
    public void withdraw(float amount)
    {
    //System.out.println("I am in ATMImplementation making a WITHDRAWAL");
    balance = balance - amount;
    }
    
    private Float balance;
    }
    
    Here is ATMProxy.java==========================
    
    package cscie160.hw6;
    
    import java.net.*;
    import java.io.*;
    
    /** Client-side proxy class which manages the connection to the
     *  server and forwards the client's requests to the server by writing
     *  the text of requests to the stream on top of the socket established
     *  at creation time when the constructor is called.
     */
    public class ATMProxy implements ATM 
    {
        private Socket socket;
        private PrintStream  printStream;
        BufferedReader inputReader;
    	
        public ATMProxy(String host, int port) throws UnknownHostException, java.io.IOException 
    	{
    		socket = new Socket(host, port);
    		OutputStream outputStream = socket.getOutputStream();
    		printStream = new PrintStream(outputStream);
    		InputStream inputStream = socket.getInputStream();
    		InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    		inputReader = new BufferedReader(inputStreamReader);
        }
    	
        public void deposit(float amount) throws ATMException 
    	{
    		// Commands is an enum in this package
    		System.out.println("ATMProxy writing command to server: " + Commands.DEPOSIT);
    		printStream.println(Commands.DEPOSIT + " " + amount);
        }
    	
        public void withdraw(float amount) throws ATMException 
    	{
    		System.out.println("ATMProxy writing command to server: " + Commands.WITHDRAW);
    		printStream.println(Commands.WITHDRAW +  " " +  amount);
        }
    	
        public Float getBalance() throws ATMException 
    	{
    		System.out.println("ATMProxy writing command to server: " + Commands.BALANCE);
    		printStream.println(Commands.BALANCE);
    		try 
    		{
    			String response = inputReader.readLine();
    			if (response != null)
    			{
    			System.out.println("Server returned: " + response);
    			return Float.parseFloat(response.trim());
    			} 
    			else 
    			{
    				throw new ATMException("ATMProxy: Unexpected end of stream reading commands in getBalance()");
    			}
    				
    		} 
    		catch (Exception ex) 
    		{
    			throw new ATMException(ex.toString());
    		}
        }
    }
    
    Here is Commands.java=====================================j
    
    package cscie160.hw6;
    
    public enum Commands 
    {
        DEPOSIT, WITHDRAW, BALANCE
    }
    Last edited by Norm; 11-12-2011 at 02:20 AM. Reason: added code tags

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    Quote Originally Posted by smartino View Post
    Here is Server.java==========================

    Java Code:
    package cscie160.hw6;
    
    import java.net.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.*;
    
    /** The intent of the Java program (Server.java) is to simulate an ATM server listening for requests from Client ATM machines.  The Server accepts the commands from Client->ATMProxy of BALANCE, DEPOSIT, or WITHDRAW.  It then calls ATMImplementation.java which in turns establishes the initial accountBalance of 0 and either adds (DEPOSIT) or subtracts (WITHDRAWS) from the accountBalance within ATMImplementation.java  Server establishes a socket on the port supplied by the argument when executed.  I uses 7777 in my examples, i.e.:  java cscie160/hw4/Server 7777
    */
    
    
    public class Server 
    {
        private ServerSocket serverSocket;
        private ATMImplementation atmImplementation = new ATMImplementation();	
        private BufferedReader bufferedReader;
        List<ATMRunnable> requestQueue;
        ATMThread[] atmthread = new ATMThread[5];
        public Server(int port) throws java.io.IOException, InterruptedException 
    	{
    		serverSocket = new ServerSocket(port);
                    atmImplementation = new ATMImplementation();
                    requestQueue = new ArrayList<ATMRunnable>();
    
        }
    
    	
        /** serviceClient accepts a client connection and reads lines from the socket.
         *  Each line is handed to executeCommand for parsing and execution.
         */
        public void serviceClient(ATMImplementation atmImplementation) throws java.io.IOException, InterruptedException
    	{
    		System.out.println("Accepting clients now");
    		Socket clientConnection = serverSocket.accept();
    		
    		// Arrange to read input from the Socket	
    		InputStream inputStream = clientConnection.getInputStream();
    		bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    		
    		// Arrange to write result across Socket back to client
    		OutputStream outputStream = clientConnection.getOutputStream();
                    PrintStream printStream = new PrintStream(outputStream);
    		
    		System.out.println("Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket");
    		
    			String commandLine;
    			while ((commandLine = bufferedReader.readLine()) != null) 
    			{
    				try 
    				{
                                      ATMRunnable atmRunnable = new ATMRunnable(commandLine, outputStream, atmImplementation);
                                      requestQueue.add(atmRunnable);
                                      System.out.println("requestQueue Size is: " + requestQueue.size());
                                      System.out.println("commandLine equals: " + commandLine);
    
    				} catch (Exception atmex) 
    				{
    					System.out.println("ERROR: " + atmex);
    				} 
    		                     ATMThread Thread1 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread2 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread3 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread4 = new ATMThread(requestQueue);		
    		                     //ATMThread Thread5 = new ATMThread(requestQueue);		
                           }
    	}
    	
    	public static void main(String argv[]) 
    	{
    
    
    		int port = 1099;
    		if(argv.length > 0) 
    		{
    			try 
    			{
    				port = Integer.parseInt(argv[0]);
    			} 
    			catch (Exception e) 
    			{ 
    				e.printStackTrace(); 
    			}
    		}
    		try 
    		{
    			Server server = new Server(port);
    			server.serviceClient(server.atmImplementation);
    			System.out.println("Client serviced");
    		} 
    		catch (Exception ex) 
    		{
    			ex.printStackTrace();
    		}
    	}
    private final int MAX_THREADS = 5;
    }
    Here is Client.java==============================

    Java Code:
    package cscie160.hw6;
    
    /** Client.java calls ATMProxy methods getBalance(), deposit(), and withdraw(), but first performing a getBalance (retrieve current balance) from Server (which in turn calls ATMImplementation.java) for current accountBalance.  Next this program calls atm.deposit with a 1000 deposit which is a DEPOSIT to Server.java, thus adding to the accountBalance in ATMImplementation.java.  Finally a withdrawal is made of $250 which is a WITHDRAWAL to Server.java, thus subtracting from the accountBalance in ATMImplementation.java.  Client takes the arguments of localhost for the network, and a port to listen on (I use 7777) in my examples.
    */
    
    public class Client 
    {
        public static void main(String[] args) 
    	{
    		try 
    		{
                // parse command line arguments
                String host = args[0];
                int port = Integer.parseInt(args[1]);
                ATM atm = new ATMProxy(host, port);
                // get initial account balance
                System.out.println("Balance: "+atm.getBalance());
                // make $1000 deposit and get new balance    
                System.out.println(" Depositing: 1000");
                atm.deposit(1000);
                System.out.println("Balance: "+atm.getBalance());
                // make $250 withdrawal and get new balance
                System.out.println(" Withdrawing: 250");
                atm.withdraw(250);
                System.out.println("Balance: "+atm.getBalance());
                // make $750 withdrawal and get new balance
                System.out.println(" Withdrawing: 750");
                atm.withdraw(750);
                System.out.println("Balance: "+atm.getBalance());
    		} 
    		catch (Exception ae) 
    		{
                System.out.println("An exception occurred while communicating with the ATM");
                ae.printStackTrace();
    		}
        }
    }
    
    
    Here is ATMThread.java=====================================
    
    
    package cscie160.hw6;
    
    import java.util.StringTokenizer; 
    import java.io.*; 
    import java.net.*; 
    import java.util.*; 
    
    public class ATMThread 
    { 
    
    Thread threadedApplication; 
    
    public ATMThread(List<ATMRunnable> requestQueue) throws InterruptedException 
    { 
    
    threadedApplication = new Thread(iterateThroughTherequestQueue(requestQueue)); 
    threadedApplication.start(); 
    
    } 
    
    
    public synchronized ATMRunnable iterateThroughTherequestQueue(List<ATMRunnable> requestQueue) throws InterruptedException
      { 
    
        ATMRunnable atmRunnableItem=null; 
    
        while(requestQueue.isEmpty()) 
               {
    
                 try
                   {
                    requestQueue.wait(); 
    
                   } catch (InterruptedException e) {
                       e.printStackTrace(); 
                   } 
               } 
    
             int requestQueueSz = requestQueue.size(); //size of the collection
                 System.out.println("requestQueue Size is: " + requestQueueSz);
             int o = 0;
    
             for(int i=0; i < requestQueueSz; i++)
                {
                 synchronized (this) {
                 atmRunnableItem = requestQueue.get(o);
                 requestQueue.remove(o); 
                 System.out.println("requestQueue Size is: " + requestQueueSz);
                 }
                }
    
            System.out.println("I am returning atmRunnableItem!!!");
    
            return atmRunnableItem; 
      } 
    } 
    
    
    Here is ATMRunnable.java===================
    
    
    package cscie160.hw6;
    
    import java.net.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import java.util.*;
    
    /** The intent of the Java program (Server.java) is to simulate an ATM server listening for requests from Client ATM machines.  The Server accepts the commands from Client->ATMProxy of BALANCE, DEPOSIT, or WITHDRAW.  It then calls ATMImplementation.java which in turns establishes the initial accountBalance of 0 and either adds (DEPOSIT) or subtracts (WITHDRAWS) from the accountBalance within ATMImplementation.java  Server establishes a socket on the port supplied by the argument when executed.  I uses 7777 in my examples, i.e.:  java cscie160/hw4/Server 7777
    */
    
    public class ATMRunnable implements Runnable
    {
        private ServerSocket serverSocket;
        Socket clientConnection;
        private ATMImplementation atmImplementation = new ATMImplementation();	
        private BufferedReader bufferedReader;
        private String commandLine;
        private OutputStream outputStream;
        private PrintStream printStream;
    
        public ATMRunnable (String commandLine, OutputStream outputStream, ATMImplementation atmImplementation) throws java.io.IOException 
    	{
             synchronized (this) {
             this.commandLine = commandLine;
             this.atmImplementation = atmImplementation;
             this.outputStream = outputStream;
           }
            }
    	
        /** serviceClient accepts a client connection and reads lines from the socket.
         *  Each line is handed to executeCommand for parsing and execution.
         */
        
        public String getCommandLine()
         {
    
           return commandLine;
         }
    
        public synchronized void run() 
    	{
    		System.out.println("Here I am!!!Threads should go here eventually...");
    		//System.out.println("this.commandLine = " + this.commandLine);
                    PrintStream printStream = new PrintStream(outputStream);
    		
    			while (this.commandLine != null) 
    			{
    				try 
    				{
    					Float result = executeCommand(this.commandLine);
    					// Only BALANCE command returns non-null
    					if (result != null) 
    					{ 
    						printStream.println(result);  // Write it back to the client
    					}
    				} 
    				catch (ATMException atmex) 
    				{
    					System.out.println("ERROR: " + atmex);
    				} 
    				
    			}
    		}
    	
    	/** The logic here is specific to our protocol.  We parse the string
    	 *  according to that protocol.
    	 */
    	private Float executeCommand(String commandLine) throws ATMException 
    	{
    		// Break out the command line into String[]
    		StringTokenizer tokenizer = new StringTokenizer(commandLine);
    		String commandAndParam[] = new String[tokenizer.countTokens()];
    		int index = 0;
    		while (tokenizer.hasMoreTokens()) 
    		{
    			commandAndParam[index++] = tokenizer.nextToken();
    		}
    		String command = commandAndParam[0];
    		// Dispatch BALANCE request without further ado.
    		if (command.equalsIgnoreCase(Commands.BALANCE.toString())) 
    		{
    		 //System.out.println("I am in getBalance  = " + commandLine);
    			return this.atmImplementation.getBalance();
    		}
    		// Must have 2nd arg for amount when processing DEPOSIT/WITHDRAW commands
    		if (commandAndParam.length < 2) 
    		{
    			throw new ATMException("Missing amount for command \"" + command + "\"");
    		}
    		try 
    		{
    			float amount = Float.parseFloat(commandAndParam[1]);
    			if (command.equalsIgnoreCase(Commands.DEPOSIT.toString())) 
    			{
    		                //System.out.println("I am in DEPOSIT  = " + commandLine);
    				this.atmImplementation.deposit(amount);	      
                                    notifyAll();
    			}
    			else if (command.equalsIgnoreCase(Commands.WITHDRAW.toString())) 
    			{
    		                //System.out.println("I am in WITHDRAW  = " + commandLine);
    				this.atmImplementation.withdraw(amount);
                                    notifyAll();
    			} else 
    			{
    				throw new ATMException("Unrecognized command: " + command);
    			}
    		} 
    		catch (NumberFormatException nfe) 
    		{
    			throw new ATMException("Unable to make float from input: " + commandAndParam[1]);
    		}
    		// BALANCE command returned result above.  Other commands return null;
    		return null;
    	}
    	
    }
    
    
    Here is Account.java=================================
    
    
    package cscie160.hw6;
    
    /** The intent of this Java program (Account.java) is to simulate a single ATM or Bank account for the user.  The accountBalance begins at zero (0) and is called from ATMImplementation.java.
    */
    
    public class Account
    {
        public Account()
            {
                    accountBalance = 10000;
        }
    public float getAccountBalance() {
    return accountBalance;
    }
    private float accountBalance;
    }
    
    Here is ATM.java===========================
    
    package cscie160.hw6;
    
    public interface ATM 
    {
    	public void deposit(float amount) throws ATMException;
    	public void withdraw(float amount) throws ATMException;
    	public Float getBalance() throws ATMException;
    }
    
    Here is ATMException.java========================
    
    package cscie160.hw6;
    
    public class ATMException extends Exception 
    {
        public ATMException(String msg) 
    	{
    		super(msg);
        }
    }
    
    Here is ATMImplementation.java======================
    
    package cscie160.hw6;
    
    /** Client-side proxy class which manages the connection to the
     *  server and forwards the client's requests to the server by writing
     *  the text of requests to the stream on top of the sockect established
     *  at creation time when the constructor is called.
     */
    public class ATMImplementation implements ATM 
    {
       public ATMImplementation()
        { 
          Account account = new Account();
          balance = account.getAccountBalance();
        }
    
    public Float getBalance() 
    {
    //System.out.println("I am in ATMImplementation GETTING A BALANCE");
     return balance;
    }
    
    public void deposit(float amount)
    {
    //System.out.println("I am in ATMImplementation making a DEPOSIT");
    balance = balance + amount;
    }
    
    
    public void withdraw(float amount)
    {
    //System.out.println("I am in ATMImplementation making a WITHDRAWAL");
    balance = balance - amount;
    }
    
    private Float balance;
    }
    Here is ATMProxy.java==========================
    Java Code:
    package cscie160.hw6;
    
    import java.net.*;
    import java.io.*;
    
    /** Client-side proxy class which manages the connection to the
     *  server and forwards the client's requests to the server by writing
     *  the text of requests to the stream on top of the socket established
     *  at creation time when the constructor is called.
     */
    public class ATMProxy implements ATM 
    {
        private Socket socket;
        private PrintStream  printStream;
        BufferedReader inputReader;
    	
        public ATMProxy(String host, int port) throws UnknownHostException, java.io.IOException 
    	{
    		socket = new Socket(host, port);
    		OutputStream outputStream = socket.getOutputStream();
    		printStream = new PrintStream(outputStream);
    		InputStream inputStream = socket.getInputStream();
    		InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    		inputReader = new BufferedReader(inputStreamReader);
        }
    	
        public void deposit(float amount) throws ATMException 
    	{
    		// Commands is an enum in this package
    		System.out.println("ATMProxy writing command to server: " + Commands.DEPOSIT);
    		printStream.println(Commands.DEPOSIT + " " + amount);
        }
    	
        public void withdraw(float amount) throws ATMException 
    	{
    		System.out.println("ATMProxy writing command to server: " + Commands.WITHDRAW);
    		printStream.println(Commands.WITHDRAW +  " " +  amount);
        }
    	
        public Float getBalance() throws ATMException 
    	{
    		System.out.println("ATMProxy writing command to server: " + Commands.BALANCE);
    		printStream.println(Commands.BALANCE);
    		try 
    		{
    			String response = inputReader.readLine();
    			if (response != null)
    			{
    			System.out.println("Server returned: " + response);
    			return Float.parseFloat(response.trim());
    			} 
    			else 
    			{
    				throw new ATMException("ATMProxy: Unexpected end of stream reading commands in getBalance()");
    			}
    				
    		} 
    		catch (Exception ex) 
    		{
    			throw new ATMException(ex.toString());
    		}
        }
    }
    
    Here is Commands.java=====================================j
    
    package cscie160.hw6;
    
    public enum Commands 
    {
        DEPOSIT, WITHDRAW, BALANCE
    }
    Not really a SSCCE. The first S stands for short

  11. #11
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Sorry, but it took me a long time just to put this all together...and I have been trying to diagnose where my error is for 2 days straight, any chance you can help?

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    I'm looking at it.
    Can you explain what it is you expect the program to do? What should the output look like?

    What does this message mean: Here I am!!!Threads should go here eventually...

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    I've been adding printlns and more printlns and more printlns.
    You should try adding some or even a lot.
    I see some output that appears to show the programming is looping.
    If you add printlns in the right places you should see it too.

  14. #14
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Thanks for looking at it. I expect the Client.java output to give me the current balance in Account.java, then add 1000 dollars by the DEPOSIT Command, and then give me an updated that adds the 1000 to the initial 10000 in the account balance, then do a withdrawal of 250 and 750, giving me updated balances along the way...

    The message "Here I am!!!Threads should go here eventually...", I put in there and others to track if I was actually getting into certain areas of the code. Just my "NewToJava" debugging skills... :)

  15. #15
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Thanks, I will give it a try...may need to wait till morning, as I have been doing this all day, thanks SO much for your help.. I will update tomorrow...

  16. #16
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    I did at one point see this when I put println's in the ATMImplementation and I would see it constantly going into these methods, but I could not find where this looping was coming from...Because I am new to threads, I just thought it was a result of the threads running....Is it threads, or truly a loop running...

  17. #17
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Ok, first I thought it was in the ATMThreads.java code, but i think that is ok...I do see it looping over and over again in ATMImplementation, but for the life of me I can't seem to fine why this is happening. Is this because of the Threads (which we just started in class), or should I be looking at for loops...I am sorry, but I have been chasing this for days, and just am not seeing it...I will check back in the morning....

    One question, Are you able to make this code work with some minor changes, so I at least know that my coding (though may not be great coding) actually has a chance of working?

    I appreciate all of your help, and I need to head to bed for some needed rest...been at this to long and can no longer make sense of what I am doing...

    THANkS AGaIN ....

  18. #18
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    I looked at this again this morning and was hoping for help in just where I should be looking, i.e.: what is causing the loop. When I put println in ATMImplementation.java, I see it is accessing the same section of the code repeatedly, in fact all of the sections in ATMImplementation.java are repeatedly being accessed when I stick println in each of them...so obviously some type of loop.

    It looks to me that the first command that the Client.java programs sends is the only one that gets executed. I tested this by taking BALANCE out of the client.java side (since this seems to be working), and put DEPOSIT in first and now it was depositing 1,000 multiple times!!! So it seems that it never gets beyond the first Command...

    Could someone please point me to at least the .java program that you feel is doing this, then I know i am working on the correct code area at least.

    thanks so much.



    Quote Originally Posted by smartino View Post
    Ok, first I thought it was in the ATMThreads.java code, but i think that is ok...I do see it looping over and over again in ATMImplementation, but for the life of me I can't seem to fine why this is happening. Is this because of the Threads (which we just started in class), or should I be looking at for loops...I am sorry, but I have been chasing this for days, and just am not seeing it...I will check back in the morning....

    One question, Are you able to make this code work with some minor changes, so I at least know that my coding (though may not be great coding) actually has a chance of working?

    I appreciate all of your help, and I need to head to bed for some needed rest...been at this to long and can no longer make sense of what I am doing...

    THANkS AGaIN ....

  19. #19
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,397
    Rep Power
    25

    Default Re: Threads!!!

    Look at where it is looping and see why the loop does not exit.
    What to you expect the output to look like if the program runs like you want it to?

    For testing could the client tell the server it is done and to exit?

    Here's the output I get when I execute my version:
    Running: F:\Java\jre6\bin\java.exe -classpath D:\JavaDevelopment;.;..\. -Xmx128M ClientServer6

    Exiting main
    S - Accepting clients now
    S - Client acquired on port #7777, reading from socket
    ATMProxy writing command to server: BALANCE
    S - requestQueue Size is: 1
    S - commandLine equals: BALANCE
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=BALANCE
    ATMR run - Threads should go here eventually... cL=BALANCE
    ATMR run println result=10000.0
    ATMProxy: Server returned: 10000.0
    C1 - Balance: 10000.0
    C2 - Depositing: 1000
    ATMProxy writing command to server: DEPOSIT
    S - requestQueue Size is: 1
    S - commandLine equals: DEPOSIT 1000.0
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=DEPOSIT 1000.0
    ATMProxy writing command to server: BALANCE
    ATMR run - Threads should go here eventually... cL=DEPOSIT 1000.0
    S - requestQueue Size is: 1
    S - commandLine equals: BALANCE
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=BALANCE
    ATMR run - Threads should go here eventually... cL=BALANCE
    ATMR run println result=11000.0
    ATMProxy: Server returned: 11000.0
    C3 - Balance: 11000.0
    C4 - Withdrawing: 250
    ATMProxy writing command to server: WITHDRAW
    ATMProxy writing command to server: BALANCE
    S - requestQueue Size is: 1
    S - commandLine equals: WITHDRAW 250.0
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=WITHDRAW 250.0
    S - requestQueue Size is: 1
    S - commandLine equals: BALANCE
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=BALANCE
    ATMR run - Threads should go here eventually... cL=BALANCE
    ATMR run println result=11000.0
    ATMProxy: Server returned: 11000.0
    C5 - Balance: 11000.0
    C6 - Withdrawing: 750
    ATMProxy writing command to server: WITHDRAW
    S - requestQueue Size is: 1
    S - commandLine equals: WITHDRAW 750.0
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=WITHDRAW 750.0
    ATMProxy writing command to server: BALANCE
    S - requestQueue Size is: 1
    S - commandLine equals: BALANCE
    ATMR - requestQueue Size is: 1
    ATMR - requestQueue Size is: 1
    ATMR - I am returning atmRunnableItem=ATMRn cmdLine=BALANCE
    ATMR run - Threads should go here eventually... cL=BALANCE
    ATMR run println result=11000.0
    ATMProxy: Server returned: 11000.0
    C7 - Balance: 11000.0
    Back from Client.main() call
    ATMR run - Threads should go here eventually... cL=WITHDRAW 250.0
    ATMR run - Threads should go here eventually... cL=WITHDRAW 750.0
    Last edited by Norm; 11-12-2011 at 03:02 PM.

  20. #20
    smartino is offline Member
    Join Date
    Sep 2011
    Posts
    64
    Rep Power
    0

    Default Re: Threads!!!

    Ok, I generated a new output, because my thought is that ATMThread.java is causing the loop based on the below output, based on the fact that i in my for loop is always equal to 0, and the requestQueueSz is always equal to 1. Does this mean that it keeps running through this loop repeatedly and executing the same return atmRunnable object?

    Say Look elsewhere if I am marching down the wrong path here...


    huit-smartino:Desktop spm888$ java cscie160/hw6/Server 7777
    Accepting clients now
    Client acquired on port #7777, reading from socket
    commandLine from Server equals: BALANCE
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    this.commandLine in ATMRunnable = BALANCE
    commandLine from Server equals: DEPOSIT 1000.0
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    commandLine from Server equals: BALANCE
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    this.commandLine in ATMRunnable = DEPOSIT 1000.0
    commandLine from Server equals: WITHDRAW 250.0
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    this.commandLine in ATMRunnable = BALANCE
    commandLine from Server equals: BALANCE
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    this.commandLine in ATMRunnable = WITHDRAW 250.0
    commandLine from Server equals: WITHDRAW 750.0
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    this.commandLine in ATMRunnable = BALANCE
    commandLine from Server equals: BALANCE
    i in the For Loop equals: 0
    o in the For Loop equals: 0
    requestQueueSz in the For Loop equals: 1
    this.commandLine in ATMRunnable = WITHDRAW 750.0
    this.commandLine in ATMRunnable = BALANCE
    done
    Client serviced

Page 1 of 4 123 ... LastLast

Similar Threads

  1. Threads
    By nsr2008.mca in forum New To Java
    Replies: 7
    Last Post: 10-18-2010, 11:47 AM
  2. Threads and UML
    By JUser in forum Advanced Java
    Replies: 0
    Last Post: 09-27-2010, 08:43 PM
  3. Threads
    By Tanuck in forum New To Java
    Replies: 5
    Last Post: 09-21-2010, 02:44 AM
  4. When to use threads
    By simorgh in forum Threads and Synchronization
    Replies: 2
    Last Post: 02-12-2010, 07:43 AM
  5. Threads
    By one198 in forum Threads and Synchronization
    Replies: 1
    Last Post: 11-20-2007, 06:15 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
  •