Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Hashtable problem when working with Threads and Sockets

Posted on 2006-03-29
8
Medium Priority
?
205 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
    }
}
0
Comment
Question by:jaycangel
  • 4
  • 2
  • 2
8 Comments
 
LVL 92

Accepted Solution

by:
objects earned 1200 total points
ID: 16319869
>    Hashtable employeeTable = new Hashtable();

should be:

   employeeTable = new Hashtable();
0
 
LVL 92

Expert Comment

by:objects
ID: 16319871
The local var shadowes the member var
0
 
LVL 6

Assisted Solution

by:avinthm
avinthm earned 800 total points
ID: 16319877
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
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:avinthm
ID: 16319882
i m late :(
0
 
LVL 1

Author Comment

by:jaycangel
ID: 16319897
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 ?!
0
 
LVL 92

Expert Comment

by:objects
ID: 16319916
create one in your Server class and pass  it as a parameter to the Cspawn constructor
0
 
LVL 1

Author Comment

by:jaycangel
ID: 16320088
Thanks, that works perfectly
0
 
LVL 92

Expert Comment

by:objects
ID: 16320186
no worries :)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month14 days, 17 hours left to enroll

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question