We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Hashtable problem when working with Threads and Sockets

jaycangel
jaycangel asked
on
Medium Priority
218 Views
Last Modified: 2010-08-05
I'm a newbit at Java, i'm having a problem with creating an employee instance. When the instance is created a hashtable is set up with with some staff information. Problem is that this information seems to be lost somewhere?!

in Client the following line getNoEmployees should write out 2, but instead i get an exception null error. Its like the employeeTable varible has been lost?! Why is this - does it have something to do with threads?

        employeeTable = new Employee();
        System.out.println(employeeTable);
        employeeTable.getNoEmployees();


I've included all my code bellow. It simply sets up a socket to wait for input from a client, that will return employee information.

Thank you for all you help,
Jason

------
import java.net.*;
import java.io.*;
import java.util.*;


/**
 * Contains employee information
 */
class Employee
{
  public Hashtable employeeTable;

  /**
   * Construct employee hashtable
   */
  public Employee()
  {
    Hashtable employeeTable = new Hashtable();
    employeeTable.put("a", "10000");
    employeeTable.put("b", "20000");
    employeeTable.put("c", "30000");
    System.out.println("Employee Table set up");
    System.out.println(employeeTable.get("a"));
  }


  public int getNoEmployees()
  {
    return employeeTable.size();
  }

  public String getSalaryOf(String i_employeeName)
  {
    return (String) employeeTable.get(i_employeeName);
  }

  public int getNoEmployeesWithSalaryGreaterThan(int i_salary)
  {
    return 1;
  }
}

public class Server extends Thread {
    private ServerSocket serverSocket;
    public  Server serverInstance;

    /**
     * Constructor to create Server
     */
    public Server() {
        try { serverSocket = new ServerSocket(2048); }
        catch (IOException e) { writeCatch(e, "Error creating server socket"); }
        System.out.println("TMA01Q2 server on port 2048");
        this.start(); // run
    }

    /**
     * Listen and respond to messages
     */
    public void run()
    {
      System.out.println("Server running");
      try
      {
        while(true)
        {
          System.out.println("Connections being accepted");
          Socket cSocket = serverSocket.accept (); // accept connection
          CSpawn c = new CSpawn(cSocket); // when connection recieved spawn new connection thread
        }
      }
      catch (IOException exp)
      {
        writeCatch(exp, "Error waiting for connection");
      }
    }

    public void isRunning()
    {
      System.out.println("is running");
    }

    /**
     * Start server
     */
    public static void main(String[] args)
    {
        new Server();
    }

    /**
     * Write out exception along with message for debugging
     */
    public static void writeCatch(Exception iExp, String iMsg)
    {
      System.out.println(iMsg + " => " +  iExp);
      Runtime.getRuntime().exit(666);
    }
}

/**
 * class handles socket threads made by client
 */
class CSpawn extends Thread
{
    private DataInputStream in;
    private PrintStream out;
    private Socket client;
    private Employee employeeTable;

    /**
     * Constructor to start connection
     */
    public CSpawn(Socket cSocket)
    {
        client = cSocket;
        try
        {
            in = new DataInputStream(client.getInputStream());
            out = new PrintStream(client.getOutputStream ());
        }
        catch (IOException exp)
        {
            try
            {
              client.close();
            }
            catch (IOException exp2)
            {
              // do nothing
            }
            return;
        }
        this.start(); // run
    }

    /**
     * Read and Analyse Input
     */
    public void run()
    {
        employeeTable = new Employee();
        System.out.println(employeeTable);
        employeeTable.getNoEmployees();

        String inputLine;
        try
        {
            while(true)
            {
                // read line from steam
                inputLine = in.readLine();
                out.println("10000");
            }
        }
        catch (IOException exp)
        {
          // ignore
        }
        finally
        {
          try
            {
              client.close();
            }
            catch (IOException exp)
            {
              //ignore
            }
        }
        // exceptions ignored because they are most likely caused by client closing
        // important exceptions are in server class
    }
}
Comment
Watch Question

Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
>    Hashtable employeeTable = new Hashtable();

should be:

   employeeTable = new Hashtable();

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
The local var shadowes the member var
Commented:
Hi ,
>   public Employee()
>   {
>     Hashtable employeeTable = new Hashtable();
>     employeeTable.put("a", "10000");
>     employeeTable.put("b", "20000");
>     employeeTable.put("c", "30000");
>     System.out.println("Employee Table set up");
>     System.out.println(employeeTable.get("a"<wbr/>));
>   }


this creates a new Hashtable

change the first line to
employeeTable = new Hashtable();

cheers

Commented:
i m late :(

Author

Commented:
Damn you are good! I've been struggling for ages!!!! And it takes you like 15 second!

Maybe you could help me with this too.

The CSpawn class contains the instance of employee. Which means that everytime someone connects to the server an new employee instance is created along with the CSpawn (connection thread). How would I change the code so that there was only one employee instance located in the server class. I just don't know how the CSpawn class would refer back to the Server class that created it. Is there something like parent.employee ?!
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
create one in your Server class and pass  it as a parameter to the Cspawn constructor

Author

Commented:
Thanks, that works perfectly
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
no worries :)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.