Socket and Thread Problem

When reading an Inputstream received after a connection has been established (throught a Socke connect) between a Server ands a Client , messages are being lost when a wait method is call. A client sents message which have to be processed and response sent back to the client . The message are encoded and as the code below shows each message ends with a '":" .Not only one message is sent at a time. and when messages are sent the client sometimes expect replies. This means that when a message is read , it be being processed by a Processor and until the reply has be sent this the thread reading the messages has to wait. when a reply is sent and the thread is waken up, the remaining the messages in the Input stream gets lost but the loop is not also exited since the end of the file is never reached.
Solution:
1. read a command message. if you find end of message, process the message and wait until you are notify and continue with the next command line
public class Sender extends Thread {
     private Socket socket;
     private Processor processor = newProcessor();
     private boolean DEBUG = false;
     public Sender (Socket socket) {
          super();
          this.socket = socket;
          start();
     public void run() {
          while (true) {
               if (processor .getStateOfProcess()&& socket != null) {
                    InputStream input = null;
                    try {
                         input = socket.getInputStream();
                         if (processor .dispatchMessage() != null) {
                              socket.getOutputStream().write(
                                        CacheManager.dispatchMessage());
                              processor .ClearMessage();
                    } catch (IOException ex) {
                    int i = 0;
                    char oldChar = ' ';
                    char c = ' ';
                    StringBuffer buffer = new StringBuffer();
                    try {
                         while ((i = input .read()) != -1) {
                              c = (char) i;
                              buffer.append(c);
                                                if (c == ':' && oldChar != '\\') {
                                   processor .process(buffer.toString());
                                   buffer = new StringBuffer();
                                   c = ' ';
                                                          try {
                                        synchronized (this) {
                                             wait();                         
                                   } catch (InterruptedException e1) {
                                                   if (processor.dispatchMessage() != null) {
                                        socket.getOutputStream().write(
                                                  CacheManager.dispatchMessage());
                                        processor.ClearMessage();
                              oldChar = c;
                                } catch (IOException e) {
   public void wakeup() {
          synchronized (this) {
               notify();
} This thread leaves that wait when the wakeup method is called in the Processor class.
Question
can some one help me figure out way and where the messages are being lost after the first message has been processed. why can the other message not be seen even other messages are still sent.
What can be a possible solution
thanks

I didn't follow all of that, but I can see one serious error in your concurrent. You should always test the condition you're waiting for inside the synchronized block - otherwise you can't be certain that wait() is called before the corresponding notify() / notifyAll() call.

Similar Messages

  • Implementing sockets and threads in a jframe gui program

    Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
    I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
    I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
    listening socket:
         private void listeningSocket()
                ServerSocket serverSocket = null;
                boolean listening = true;
                try
                    //listen in port 4444;
                    serverSocket = new ServerSocket(4444);
                catch(IOException x)
                    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
                while(listening)
                    client_thread w;
                    try
                       w = new client_thread(serverSocket.accept(), jTextArea1);
                       Thread t = new Thread(w);
                       t.start();
                    catch(IOException x)
                         JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
            }thread class:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.event.*;
    * @author jonathan
    public class client_thread extends Thread
         //define new socket object
        private Socket client_user = null;
        private JTextArea textArea;
        public client_thread(Socket client_user, JTextArea textArea)
            this.client_user = client_user;
            this.textArea = textArea;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured, messege was not sent";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   textArea.append(messege);
            catch (IOException e)
                //error messege
                JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
    }

    Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
    I would say in your thread class do the following:
    MyConversationDialog dialog = new MyConversationDialog();
    while(true)
                   //read messege sent by user
                   messege = in.readLine();
                    //display messege in textfield
                   out.println(messege);
                   dialog.setVisible (true);
                   dialog.addMessage (message);
                }

  • Sockets and thread communication multiplexing?

    Hello,
    I need to implement a server which will have a maximum of 10 clients connected.
    I wanted to go for classic blocking I/O because I won't have much clients.
    My problem is that even if I accept() some sockets and then create a thread for each socket,
    then I still need to communicate some data to the other threads, problem is that I am blocked
    on the read() operation, how could I address this problem?
    I mean, lets say I am thread1 and blocked on read() on my socket, now thread7 wants to tell
    me something like a chat message coming from client he handles, how could thread7 manage
    to wake thread1 and send him a message somehow?
    I do not want to deal with NIO stuff if possible because I do not need to scale, I just have a
    problem because I am stuck on the read.
    I will run on Windows.
    Thanks for help.
    Edited by: Marzullo on Jul 15, 2010 1:05 PM

    Fully answered in [your other thread|http://forums.sun.com/thread.jspa?threadID=5445070&messageID=11020688#11020688].
    Please don't multipost, as it can lead to people wasting their time repeating others' answers.

  • Problem with socket and Threads

    Hi,
    I have coded a package that sends an sms via a gateway.
    Here is what is happening:
    * I create a singleton of my SMSModule.
    * I create an sms object.
    * I put the object in a Queue.
    * I start a new Thread in my sms module that reads sms from queue.
    * I connect to sms gateway.
    * I send the sms.
    * I disconnect from socket! This is where things go wrong and I get the following error (see below).
    I have a zip file with the code so if you have time to take a look at it I would appreciate it.
    Anyway all hints are appreciated!
    //Mikael
    GOT: !LogoffConf:
    mSIP Kommando var: !LogoffConf
    CoolFlix log: MSIPProtocolHandler;setLoggedin(false)
    We got LogOffConf
    Waiting ......for thread to die
    java.net.SocketException: Socket operation on nonsocket: JVM_recv in
    socket input stream read
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:116)
    at
    sun.nio.cs.StreamDecoder$CharsetSD.readBytes(StreamDecoder.java:405)

    Off the top of my head, probably the garbage collector cleared your SMSModule coz all classes loaded through other classloaders will be unloaded when that classloader is unloaded.
    mail in the code if you want me to look at it with greater detail.

  • Socket and threads.

    I have written a socket client and a socket server. The client sends a directory name and the server sends directory files and their content. The client asks for files every five seconds (it has to be made once every day, but for trials I have reduced the time), so I have written a thread to made the client sleep for that time. The problem appears after looping fifty or sixty times, when the socket, which does not die, stops making its work (files are not send any more). I really thank every answer.

    Please be clear. What "stops work" the client or the server? Can you post the relevant code that is "looping fifty or sixty times"?

  • Socket and Thread Question?

    I have a Server/Client app where the Client connects to the server and the server accepts the Client and starts a new thread for each client.
    Then the Server Thread waits for the Client to contact.
    I set the timeout on the Server socket to 30 seconds.
    but the Client could sit there idle for much longer.
    So on the client side i used a timer to send "-1" every 5 seconds.
    That way if the Server Thread times out i know the Client is not there and end the thread and close everything.
    Now on the client side i may send several strings in a row to the server so i do not want my "-1" timer (i'm still here) messages to get intermingled with regular Client messages so i set up a boolean variable like so:
        volatile private boolean out1busy = false;
        private synchronized boolean getOut1busy(){
         return out1busy;
        private synchronized void setOut1busy(boolean on){
         out1busy = on;
        }then before using the socket i do this:
            while (getOut1busy()) try { Thread.sleep(40); } catch (InterruptedException ex) {}
            setOut1busy(true);
            lobbyOut.println("-1");
            setOut1busy(false);I have been running this for over a year and have personally never had a problem but have had rare clients testing say their comp has suddenly bogged down and it seems like they are describing what might happen if Out1Busy is set to true and not set back to false.
    ive checked my code and like i say it has never happened to me BUT i feel like what i am doing here is not the right way and there is probably a much better way to accomplish this. It is the only place in my code i see the chance of an infinate loop occuring.
    So regardless of whether or not it is even causing a problem can anyone tell me if it might cause a problem and a better way to do it.

    how about this.
    everywhere that i send data to the server that is not already on the event dispatch thread i just put in an invoke later which wold execute it on the eventdispatch thread.
    that way all communication with the server would be done on the event dispatch thread.
    so if i click a button that sends several strings right in a row it would complete before the "-1" im still here message sent at the same time goes through.
    so even if i had two bits of code that send several strings that need to be received in a row they would not get intermingled as long as they were both executed within a invokelater or already executed on the event dispatch thread (like a mouse clicked or action performed)
    so in my case here i always contact the server in either a state changed, action performed, or mouseclicked except for the "-1" im still here message.
    are alll these (state changed, action performed, or mouseclicked) executed on the event dispatch thread?
    i just put the "-1" in an invoke later and take out all the sleep and outbusy variable stuff.

  • Socket and multithreading problem (flow control)

    This code is heavily influenced by the KKMultiServerThread. I am having problems controlling the thread flow.
                 login = new MultiServerThreadLogin(serverSocket.accept(), serverSocket);
            login.start();     
              while(true){
                 System.out.println(login.getAuthen());
                 while(login.getAuthen()){
                      System.out.println("doing hello");
                      hello = new KKMultiServerThread(serverSocket.accept(), serverSocket);
                      hello.start();
                      if(hello.getFlag())
                      break;
              }here, you can see that i am trying to start a thread to login the user and then recieve files from the cilent. When my GUI runs, there is no problem whatsoever that is for the 1st time, however when i try running the 2nd time, the code as u can see, doesnt allow that... so is there anyway to break away from the inner loop?

    hey thanks for replying... i'm sorry but in a rush here...
    this snippet resides in the server. There are 2 classes, namely MultiServerLoginThread and KKMultiServerThread, both extends Thread.
    The function of the MultiServerLoginThread is to read in bytes of Secretkey, username(encrypted) and password(encrypted). This should only take place once.
    The function of theother thread, KKMultiServerThread is to read in the file name to be transferred and the contents. This is based on the KKMultiServerThread which can be found somewhere in this forum... i hope...
    The KKMultiServerThread is started over and over because the client is sending multiple files. Hence the while loop. However after sending the last file, it should go to the MultiServerLoginThread....
    One thing i don't really get it is that if i were to do this(put the creation of the login thread within the while loop):
    while(true){
                 System.out.println(login.getAuthen());
                 login = new MultiServerThreadLogin(serverSocket.accept(), serverSocket);
            login.start();
                 while(login.getAuthen()){
                      System.out.println("doing hello");
                      hello = new KKMultiServerThread(serverSocket.accept(), serverSocket);
                      hello.start();
                      if(hello.getFlag())
                      break;
              }The GUI totally hangs.
    More explanation...
    hello.getFlag() returns the flag when the client has finished sending all the files
    login.getAuthen() returns whether the user has successfully logged in with correct creditials

  • Chatserver socket and port problem

    hi,all.
    i write a chat server use java socket. now is more than 2000 users connect to my server. but too many user make the chat message speed slow. now my server is open one port to listen the client connection. who can tell me if i change my server to open multi port to listen the client connection will rather than open one port. or it is same effect.
    please give me some advice. thanks.
    my homepage is:http://www.easyfad.com

    my server system resource is no problem. Have you timed the bus on your machine?
    18% of memory means physical or total. If total is that 18% hitting the hard drive?
    What is your actual network speed? A 100m ethernet has a theoretical speed of about 12 meg per second, in practice you will never get even close to that. A normal ftp transfer might only get 500k per second. And networks can be significantly overloaded.
    What are the configuration parameters for your IP stack? It might be configured incorrectly for the type of traffic and quality of traffic that you are getting.
    The above are all possible things that can affect performance. And there are probably more. Standard OS tools are NOT the best way to measure platform performance. They can often provide misleading numbers, even when one knows what the numbers really mean.
    if i use multi port to create socket connection,
    if it will help to increase message sending speed ? Like I said I can't see how. Something is causing a slowdown. Your NIC can only process so much traffic. If your NIC was the bottle neck and you had two NICs then that would help. But if it was me I really wouldn't try a two NIC solution until I had exhausted every other possibility. First because it is unlikely to the be bottleneck and two because setting up a 2 NIC (or more) server is not plug and go solution.

  • Socket and Thread Explanation

    I'm a little confused on the Socket stuff. I read some tutorials but wanted to make sure I understand. I'm using a simple client/server chat app as a reference.
    First the ServerSocket is just a connection to the port you want to listen on... I understand that. Is the Sockets... Socket s = ss.accept(); a tunnel to the port for data to travel on?
    Second.. When you create a Thread. This is the information that travels on these sockets? If that's the case I understand... But I have one question relating to some chat code I can't quite figure out.
    The simple chat program conists of a ChatServer, ServerThread and a Client.
    in the ChatServer it creates a ServerSocket and later on it looks for new connections for clients and then creates a ServerThread. What the heck is this for. From the code in the ServerThread it just handles incoming data and sends them back out. OK.
    But in the Client... it connects to this port and then creates it's own thread i.e. new Thread(this).start();
    Why ServerThread and then a Thread from the Client... Shouldn't there just be one?
    Sorry, I just can't get this.

    I'm a little confused on the Socket stuff. I read
    some tutorials but wanted to make sure I understand.
    I'm using a simple client/server chat app as a
    reference.
    First the ServerSocket is just a connection to the
    port you want to listen on... I understand that. Is
    the Sockets... Socket s = ss.accept(); a tunnel to
    the port for data to travel on?when the accept() method called, the server socket will start listening to the port for any connection. Once a connection established, this method will return a connected socket.
    >
    Second.. When you create a Thread. This is the
    information that travels on these sockets? If that's
    the case I understand... But I have one question
    relating to some chat code I can't quite figure out.A new thread was created here to that this thread can handle the socket return by the serversocket independenty to the main thread. Mainly server code will do this so that the main thread can continue to listening to other new connection agains while this newly created thread will handle any communication between a connected client and server.
    The simple chat program conists of a ChatServer,
    ServerThread and a Client.
    in the ChatServer it creates a ServerSocket and later
    on it looks for new connections for clients and then
    creates a ServerThread. What the heck is this for.
    From the code in the ServerThread it just handles
    incoming data and sends them back out. OK.
    But in the Client... it connects to this port and then
    creates it's own thread i.e. new Thread(this).start();Well, i dun know how the code for the client look like... but guessing that the client was implements Runnable. So, in the main method, it spawn a new thread and pass this class for this new thread to handle while the main thread maybe continue to do other things or just end after finish.
    >
    Why ServerThread and then a Thread from the Client...
    Shouldn't there just be one?
    Sorry, I just can't get this.Well, hope my explaination was clear enough... :P

  • Socket and Thread fun

    I am currently playing around with a, MUD like, program.
    I have 2 classes, server class who's main function is to listen to the port and create a new client class with the value of the incomming socket.
    The client class extends Thread, and pretty much just processes the input from the client socket.
    Now this is all good until I wanted to have multiple clients and have them talking to each other. I thought that having a Vector and storing the sockets in another class was the way to go. But whenever I refer to Vectors and Sockets I get the following runtime error :
    java.lang.NullPointerException
    at Controller.addSocket(ClientConnection.java:62)
    at ClientConnection.run(ClientConnection.java:35)
    Where line 35 is sending the socket to the class that adds it to the Vector, and 62 is trying to add the Socket to Vector.
    What am I doing wrong? Is there a better way of doing it, and if so a link to an example would be good.
    Cheers
    Shane

    From the stack traces, it is saying that the Controller is a null object. Probably you forgot to call on new Vector(), or you declared it twice in the constructor. There could also be a possibility that the socket passed to it was null.

  • Multi channel design issue - sockets and threads

    How are multiple channels handled in a chat program? Does the server separate the channels by having a port open for each channel, or is it done some other way?
    Thanks

    Yes it is possible. A user is logged on as long as the applet has a socket connection that has passed the login phase.
    Keep a server on the web site that handles the chat stuff. If you want to show some statistics like the users logged on, you can access the server from your local web site and ask him what's going on.
    You can do this with an administrative command set (your statistics module has to login to the server just like a chatter), with a special tcp port or with thread communication. In the latter case server and servlet would have to reside in the same JVM which is not really trivial...
    Another approach is to write the statistics into a shared file, and read this file from your web server.
    -- Stephan

  • Synchronization and threads problem

    Hi, i'm a novice to java.i got an assignement where i'm suppose to emulate a bus actions(picking on and dropping of people).
    It has 4 main class , i'm using netbean as IDE.
    The bus have 5 station(1,2,3,4,5) and goes to them one after another picking up passenger ad dropping them off.It have max capacity of 2 passenger at a time.It's able to pick the first passenger and leave when it reaches the 2nd station and pick the second passenger it hang as if in an infinite loop.
    Here are the classes in use and screenshot depicting the sittuation:
    Bus :
    * Bus.java
    * This class represents the bus,
    * a resource shared by passengers and the control system.
    package busservice;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;
    class Bus
    public enum Direction{UP, DOWN};
    private int position; // bus's currrent position, i.e. bus stop.
    private int increment; // bus's currrent increment +1 for UP, -1 for DOWN
    private Direction busDirection;// bus's current direction - UP or DOWN
    private int available; // available seats
    private ReentrantLock bus = new ReentrantLock();
    private Condition[] arrive = new Condition[Main.BUS_STOPS+1]; // index 0 unused
    public Bus()
    available = Main.CAPACITY;
    position = 1;
    increment = 1; // Initially travelling in UP direction
    busDirection = Direction.UP;
    System.out.println(Main.spaces(position) + labelledBus()+ " arrives");
    for (int i = 1; i <= Main.BUS_STOPS; i++)
    arrive[i] = bus.newCondition();
    // method called by a passenger wishing to get on the bus at bus stop
    public void getOn(int fromStop)
    bus.lock(); //passenger obtains resource
    try{
    while (position != fromStop || available == 0)
    arrive[fromStop].await();
    arrive[fromStop].signal();
    available--;
    catch(Exception e)
    e.printStackTrace();
    finally{
    bus.unlock();
    bus.notifyAll();
    // Method called by passengers wishing to get off the bus at bus stop.
    public void getOff(int toStop)
    bus.lock();
    try
    while (position != toStop)
    arrive[toStop].await();
    available++; // passenger gets off train
    catch (InterruptedException e)
    e.printStackTrace();
    finally
    bus.unlock();
    // returns a string showing the direction and occupancy status of the bus
    private String labelledBus()
    String emptySeats = "...................".substring(0, available);
    String fullSeats = "*******************".substring(0, Main.CAPACITY - available);
    if (busDirection == Direction.DOWN)
    return ("<BUS["+emptySeats+fullSeats+"]");
    else
    return ("["+fullSeats+emptySeats+"]BUS>");
    // Method called by control system to move bus to next bus stop
    public void move()
    bus.lock();
    try // bus leaves one bus stop and travels to next one
    System.out.println(Main.spaces(position) + labelledBus()+" leaves");
    Thread.sleep(Main.TRAVEL_TIME * 1000);
    position = position + increment;
    System.out.println(Main.spaces(position) + labelledBus()+ " arrives");
    // Reverse direction if at end of route
    if ((busDirection == Direction.UP) && position == Main.BUS_STOPS)
    increment = - increment;
    busDirection = Direction.DOWN;
    else if ((busDirection == Direction.DOWN) && position == 1)
    increment = - increment;
    busDirection = Direction.UP;
    arrive[position].signalAll();
    catch (InterruptedException e)
    e.printStackTrace();
    finally{
    bus.unlock();
    }Controler class
    * Control.java
    * This class implements the bus control system.
    package busservice;
    class Control extends Thread
    private Bus bus;
    private volatile boolean end = false;
    public Control(Bus bus)
    this.bus = bus;
    public void run()
    while (!end)
    try
    sleep(Main.WAIT_TIME * 1000);
    bus.move();
    catch (InterruptedException ex)
    ex.printStackTrace();
    return;
    public void finish()
    end = true;
    }Passenger
    * Passenger.java
    * Implements a bus passenger as an autonomous thread.
    package busservice;
    import java.util.concurrent.CountDownLatch;
    class Passenger extends Thread
    private int id; // unique id, from 1 to Main.PASSENGERS
    private int from, to; // start and end bus stops
    private Bus bus;
    private CountDownLatch CountDown;
    Passenger(int id, int from, int to, Bus bus, CountDownLatch CountDown)
    this.id = id;
    this.from = from;
    this.to = to;
    this.bus = bus;
    this.CountDown = CountDown;
    public void run()
    CountDown.countDown();
    System.out.println(Main.spaces(from) + 'P' + id + " arrives");
    bus.getOn(from);
    System.out.println(Main.spaces(from) + 'P' + id + " gets on");
    bus.getOff(to);
    System.out.println(Main.spaces(to) + 'P' + id + " gets off");
    this.notify();

    * Bus.java
    * This class represents the bus,
    * a resource shared by passengers and the control system.
    package busservice;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;
    class Bus
    public enum Direction{UP, DOWN};
    private int position; // bus's currrent position, i.e. bus stop.
    private int increment; // bus's currrent increment +1 for UP, -1 for DOWN
    private Direction busDirection;// bus's current direction - UP or DOWN
    private int available; // available seats
    private ReentrantLock bus = new ReentrantLock();
    private Condition[] arrive = new Condition[Main.BUS_STOPS+1]; // index 0 unused
    public Bus()
    available = Main.CAPACITY;
    position = 1;
    increment = 1; // Initially travelling in UP direction
    busDirection = Direction.UP;
    System.out.println(Main.spaces(position) + labelledBus()+ " arrives");
    for (int i = 1; i <= Main.BUS_STOPS; i++)
    arrive[i] = bus.newCondition();
    // method called by a passenger wishing to get on the bus at bus stop
    public void getOn(int fromStop)
    bus.lock(); //passenger obtains resource
    try{
    while (position != fromStop || available == 0)
    arrive[fromStop].await();
    arrive[fromStop].signal();
    available--;
    catch(Exception e)
    e.printStackTrace();
    finally{
    bus.unlock();
    bus.notifyAll();
    // Method called by passengers wishing to get off the bus at bus stop.
    public void getOff(int toStop)
    bus.lock();
    try
    while (position != toStop)
    arrive[toStop].await();
    available++; // passenger gets off train
    catch (InterruptedException e)
    e.printStackTrace();
    finally
    bus.unlock();
    // returns a string showing the direction and occupancy status of the bus
    private String labelledBus()
    String emptySeats = "...................".substring(0, available);
    String fullSeats = "*******************".substring(0, Main.CAPACITY - available);
    if (busDirection == Direction.DOWN)
    return ("<BUS["+emptySeats+fullSeats+"]");
    else
    return ("["+fullSeats+emptySeats+"]BUS>");
    // Method called by control system to move bus to next bus stop
    public void move()
    bus.lock();
    try // bus leaves one bus stop and travels to next one
    System.out.println(Main.spaces(position) + labelledBus()+" leaves");
    Thread.sleep(Main.TRAVEL_TIME * 1000);
    position = position + increment;
    System.out.println(Main.spaces(position) + labelledBus()+ " arrives");
    // Reverse direction if at end of route
    if ((busDirection == Direction.UP) && position == Main.BUS_STOPS)
    increment = - increment;
    busDirection = Direction.DOWN;
    else if ((busDirection == Direction.DOWN) && position == 1)
    increment = - increment;
    busDirection = Direction.UP;
    arrive[position].signalAll();
    catch (InterruptedException e)
    e.printStackTrace();
    finally{
    bus.unlock();
    }Controler class
    * Control.java
    * This class implements the bus control system.
    package busservice;
    class Control extends Thread
    private Bus bus;
    private volatile boolean end = false;
    public Control(Bus bus)
    this.bus = bus;
    public void run()
    while (!end)
    try
    sleep(Main.WAIT_TIME * 1000);
    bus.move();
    catch (InterruptedException ex)
    ex.printStackTrace();
    return;
    public void finish()
    end = true;
    }Passenger
    * Passenger.java
    * Implements a bus passenger as an autonomous thread.
    package busservice;
    import java.util.concurrent.CountDownLatch;
    class Passenger extends Thread
    private int id; // unique id, from 1 to Main.PASSENGERS
    private int from, to; // start and end bus stops
    private Bus bus;
    private CountDownLatch CountDown;
    Passenger(int id, int from, int to, Bus bus, CountDownLatch CountDown)
    this.id = id;
    this.from = from;
    this.to = to;
    this.bus = bus;
    this.CountDown = CountDown;
    public void run()
    CountDown.countDown();
    System.out.println(Main.spaces(from) + 'P' + id + " arrives");
    bus.getOn(from);
    System.out.println(Main.spaces(from) + 'P' + id + " gets on");
    bus.getOff(to);
    System.out.println(Main.spaces(to) + 'P' + id + " gets off");
    this.notify();
    }

  • Java with Derby embedded and threads - problem?

    Hello,
    been developing java app and recently switched to derby database. At first i insert some data into derby and my app populates fine. However when my app creates a new thread (to do something in background and then updates the derby database) it all goes wrong. The thread is not responding and the database is not updating..
    What could this be?
    Could this be a database issue with java,jdbc, derby or just threads in general?
    It was working before previously with my previous database: MySQL which runs in a separate process but an embedded derby just wont make it happen.

    you're probably right that i'm making conclusions early but i've done everything i could and the feeling is like you want to give up. You feel de-motivated.
    I've been switching a lot of databases and trying them out and it seems that i can't get it to work with the embedded databases for some reasons. Could it possibly be some other stuff that i'm running in the background.
    Because, my background tasks is really heavy:
    - it creates a few threads to do tasks which some of them recieve information remotely from other machines, a few loops here and there, a few other threads with starts up a few processes (external exe's) to do some work and finally a few threads to do some calculation & update the database..
    But on the brightside i know my app works with my local MySQL database which runs in a separate process. I can also get my app to work with an online database on a hosting site - but the connection is very very slow (20 times as much time it takes to connect, i actually timed it.)

  • Socket and PORT problem

    I am new to socket programming. Is there a command in UNIX to see which ports are not occupied?
    Since I have problem right now in my program to close the sockets, will they be closed automatically after I interrupt the program, should I close it manually from the command line?
    TIA.
    mmc

    When you create a Socket, you can either bind to port 0 (which binds to the first available port) or to any other valid Port number. There is no Java-based method for geting the port numbers in-use or available. When your program terminates, the sockets will terminate as well, but the port may not be available for use for a few seconds. This allows for the system to be reset.

  • Timer, socket, and thread

    I need to write a code that will open and write on/to a socket in less than two minutes. what classes should i have? I know I need the timer and socket, but which one should i use first? open a socket first than create a timer, or the other way? I'm new to this all OO stuff

    I need to write a code that will open and write on/to
    a socket in less than two minutes. ???
    what classes
    should i have? I know I need the timer and socket,
    but which one should i use first? open a socket first
    than create a timer, or the other way? I'm new to
    this all OO stuffhttp://java.sun.com/docs/books/tutorial/
    http://java.sun.com/docs/books/tutorial/essential/concurrency/
    http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter08/timers.html
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

Maybe you are looking for

  • I can't use the Mail app after updating to 8.0.2

    I can add my Gmail account to my phone just fine.  It adds my calendar, my contacts and my notes with no problem.  But when I open the Mail app, I get a blank screen.  It stays blank for about 15-20 seconds and then closes automatically. Also, there

  • Messages stopped working with my phone number all of a sudden?

    Hi In the last few weeks since retruning from a trip to the UK the messages on my MacBookPro is not working/syncing with my phone numbers... has anyone else found this? Im using OS X 10.8.3 and 6.1.3 on my iphone and previously I had two phone number

  • How to change the attributes of screen fields dynamically

    <b></b> well i have created a table by name empmaster_data with following fields. *emp_id. *emp_fname. *emp_lname *dob. *doj. *dept. *desig. now using a single screen i want to create,change and display the information.even i am using save and exit b

  • Upgrade 9.2.0.8 to 11gR2 optimizer plan stability

    Hi, We plan in upgading our Oracle 9.2.0.8 to 11g R2 soon. We are using HP-UX Itanium. We have concern about our applications and reports performance after upgrade, and we are preparing test plan for this. On of the plan is collecting all of the exec

  • Error deploying BPEL process

    Hi, I am following the SOA Order booking tutorial (chapter 7: Creating the SelectManufacturer Project). When I try to build the BPEL Process, I get the following error: Buildfile: C:\Jdev10g\jdev\SOADEMOLAB\SelectManufacturer\build.xml pre-build: val