NIO issue - writing to sockets from 2 threads

Hi All,
I have some questions regarding a NIO-server i'm developing. I have read many posts relating this issue, but still...
I have one thread that does the Selector.select() and read & write to the sockets
I have another thread that uses the same Selector and changes the interestOp to OP_WRITE (then wakes up the Selector).
I have a Connection (attachment) that i use to hold the inputBuffer and outputBuffer to handle remainings.
I've read a post in which some ppl wrote the stages of using th OP_WRITE and it was suggested that only when i wanna write i'll add the OP_WRITE and exclude it in the isWritable() - so i'm doing that.
My questions are:
1. Is it safe to change the interestOp on a key from another thread?
2. What happens if the select() is in process?
3. Are there any other problems with my implementation?
4. What other way i have to write to a socket from 2 different threads (withough putting a lock on the socket)?
Thanks.

Reset your thinking a bit. You should only register for OP_WRITE when you have just executed a 'short write', i.e. a return value > 0 but < the length you asked to write, and you should deregister OP_WRITE any time you execute a 'complete write', i.e. a write which writes everything you asked for. At all other times you should just write and handle your own syncrhonization. The reason is that socket channels are almost always writable except under the condition described so you will just be returning early from select() for nothing.

Similar Messages

  • Thread issue when delete socket

    I've got a new problem: when I try to close the socket by deleting it, a thread marshalling issue has appeared:
    void MainPage::PutOutFire()
    if (CoreApplication::Properties->HasKey("client"))
    // Remove the socket from the list of application properties as we are about to close it.
    StreamSocket^ socket = dynamic_cast<StreamSocket^>(CoreApplication::Properties->Lookup("client"));
    CoreApplication::Properties->Remove("client");
    // Close the socket.
    Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, &socket]()
    if (socket)
    delete socket;//pivot of crash!!!
    socket = nullptr;
    bIsConnected = false;
    NotifyUser("Client closed.", NotifyType::StatusMessage);
    else
    NotifyUser("Client already closed or not connected.", NotifyType::WarningMessage);
    This is called by the button event handler.
    Then I get this error:
    Microsoft C++ exception: Platform::WrongThreadException ^ at memory location 0x0545DD48. HRESULT:0x8001010E The application called an interface that was marshalled for a different thread.
    WinRT information: The application called an interface that was marshalled for a different thread.
    I used the Dispatcher, and I put it in the UI thread, but the issue is still there.

    I don't think you have to delete it. Just set it to nullptr, it will self destruct by itself due to ref counting.

  • Closing socket connection from 2nd thread

    I did some research on different operating systems to find a unique solution how to timeout a blocking recv call in one thread.
    Closing the connection from another thread helps but I found that there are two different methods how to close the connection:
    - either just calling close with the correct linger options
    - call shutdown first and then close
    Unfortunately most platforms work fine with only one of these methods and fail more or less severe with the other method.
    While I think to fully understand the behavior of Windows and Linux, Solaris is still a big question mark for me.
    I have some machines (running Solaris 8, 7 and 2.6) which work well with just closing and crash the system when using shutdown (while having bad luck in the timing of the other peer). And I have another 2.6 machine that behaves the other way around.
    I created a detailed description about the whole problem and my findings in a PDF if you are interested: http://www.webwasher.com/download/notes/timeoutblockingsocketcall.pdf
    Is anybody able to explain how the Solaris implementation works here?
    And does anybody know why I see the differences with the two 2.6 boxes? (I changed patch level and exchanged clib without success.
    Martin

    I have a main program which creates a thread.Why not create a thread once the object has been read.
    The thread would take some time to process this
    object before it accepts another object to be passed
    in from the main program.Threads are used for concurrent execution. If you don't want concurrent execution, don't use additional threads. Have the main program do the reading and execution and then it cannot read another object until it has finished executing the previous one.
    >
    However, I realise that my main program:
    s = new Socket("localhost", 2001);
    will produce a socket connection
    socket connection even if the thread is still
    processing the object. Why is this possible?This is what threads do. It is call multi-threading.
    Initially I thought the thread would lock the socketIt will lock the sockect when you lock it with synchronized. Howver you are creating a new socket each time so even this would not do what you suggest.
    and my main program would not be able to get a socket
    connection until my thread releases the socket.Everytime you call new Socket() it creates a NEW socket. You can open as many socket as the server can handle. (10000+)
    Code in my thread to accept a socket connection:
    server = new ServerSocket(2001);
    ois = new ObjectInputStream(server.accept().getInputStream());I would suggest putting the Socket created by server.accept() into a variable. Otherwise you will not be able to reply to the request, nor will you be able to close() the connection.
    How can I workaround this issue. Hope somebody can help. Thanks.You don't need a workaround, you need to fix the logic of your application.

  • I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with emails from this thread. I used the action within the thread that says stop following but appears to have no effect I stil

    I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with  emails from this thread. I used the action within the thread that says stop following but appears to have no effect I still keep  getting from 5 to 20 emails daily. Please help!!!!!!!

    This may be helpful: How do I disable email notifications?

  • Possible thread issues when calling java from C++/Delphi/C#

    Hi,
    We have a java API for one of our applications. This API has wrapper API's in C++, Delphi and C#. There are two main top level classes in te API - Client and Receiver. Both haave a receive() method.
    We used to ship JRE1.3 with the API installation - this was needed to suport the user applications. Recently we haev moved to java 1.4 as the least suported version.
    We have two ways of using the java API in our wrapper API's.
    Method one, we instantiate the client, and call client.receive(). There are no threads etc involved here. This is working fine.
    In the second method, we set a callback on the client, which starts a thread (in C++/Delphi or C#) which calls receiver.receive() and tries to get the message. This is failing.
    It fails at a line which simply says "DocumentBuilderFactory.newInstance()".
    This call has already been made when connecting the client and it is successful because we can see the client connected.
    Whether we do client.receive() or receiver.receive() in a thread, the code passes through this line.But is throwing the exception only when we come to it through a thread.
    Any ideas on what I need to watch out for when calling methods on a JVM from a thread in C++/Delphi or C#?
    Thanks
    Hari
    PS: I know we are using some really old versions, but thats needed and out of my control.

    Hi,
    I managed to solve this - finally!
    This is what was the cause in our case - should apply to all situations though.
    We had the Xerces classes packaged in a custom jar file along with other XML stuff we have. And this mega-jar was on the class path.
    We were running everything on Java 1.3 and it worked fine.
    But Java 1.4 wrecked all havoc.
    So here is what I did:
    1. I tried explicitly doing Class.forName() with the name of the Xerces class that was not found. I did this at the same point in the code where the exception was being thrown.
    2. The class was successfully loaded indicating that it was on the class path somewhere.
    3. Java 1.4 made some changes in terms of class loaders - so suspecting that, I tried printing out the System and the Context class loaders at the point where the exception was being thrown - the system class loader was a valid object, but context class loader was null
    4. We have another point in the code base where the exact same lines were used, and these are getting successfully executed even in the multi threaded situation - this is the start up sequence.
    5. I printed the two class loaders at this point - they are both valid objects, no nulls.
    With this, I narrowed down the scope and was convinced that the class loaders are the cause.
    A search on Google and after looking the the source code for Xerces, we realized that the Xerces API uses the Context Class Loader to resolve and load the DocumentFactoryImpl class - this change is from Java 1.4 onwards.
    In our case, the JNI AttachCurrentThread method called from C++/C# and Delphi was attaching the thread to the JVM, but each time the context class loader was null.
    We could not find anything on how we could make the method to put a non null context classloader.
    So, we changed all our JNI interfaces to do the following
    //attach the current thred
    jvm->AttachCurrentThread(...)
    //now get the system class loader and set it as the context class loader on the current thread
    //get things from the Thread class
    jclass thread = get the thread class
    jmethod currentThread = get the static method currentThread()
    jobject thread_object = get the current thread object into this
    jmethod setContextClassLoader = get the setContextClassLoader() method on the thread
    //get the SystemClassLoader
    jclass clsLoader = get the class for ClassLoader
    jmethodid getSysClsLoader = get the method ID for the getSystemClassLoader() method
    jobect sysClsLoader = get the system class loader by calling the above method
    //set the context class loader on the thread by calling set context class loader with the sys class loader as the argumentUnfortunately I don't have the code with me right now,otherwise would have shared the same.

  • NIO: issues with the IO part

    I've been working on a multi client/ server system, and I had success with traditional networking using Sockets, streams and Threads to handle each connection. In an attemp to make my srver more efficient using asynchronous communication (which I am forever regretful for) I have completely destroyed all funtionality of the program. My server is now successfully asynchronous, but it does not communicate.
    I have tried an and all variations of sockets, streams, socketChannels, Readable/Writeable ByteChannels, ObjectInput/OutputsStreams, and nothing is working. It comes to the same part each and every time and fails to continue. I'm trying to read in an array of characters from the SocketChannel, and parse them with basic ByteBuffer get commands. The Client seems to be writing the buffer which I know is properly filled with data, but the server side socket never recieves it, it just holds, or when I have it set to non blocking, returns null on the read() command.
    Heres some of the code for the server. If it looks familiar its because I got it from a tutorial off IBM after getting frustrated and deleting my original code.
    Selector selector = Selector.open();
    // Open a listener on each port, and register each one
    // with the selector
    ServerSocketChannel serverSocket = ServerSocketChannel.open();
    serverSocket.configureBlocking( false );
    ServerSocket ss = serverSocket.socket();
    InetSocketAddress address = new InetSocketAddress( port );
    ss.bind( address );
    SelectionKey Acceptkey = serverSocket.register( selector, SelectionKey.OP_ACCEPT );
    while (true) {
    int num = selector.select();
    Set selectedKeys = selector.selectedKeys();
    Iterator it = selectedKeys.iterator();
    while (it.hasNext()) {
    SelectionKey key = (SelectionKey)it.next();
    if ((key.readyOps() & SelectionKey.OP_ACCEPT)
    == SelectionKey.OP_ACCEPT) {
    // Accept the new connection
    ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
    SocketChannel sc = ssc.accept();
    sc.finishConnect();
    sc.configureBlocking( false );
    // Add the new connection to the selector
    SelectionKey newKey = sc.register( selector, SelectionKey.OP_READ);
    it.remove();
    System.out.println( "Got connection from "+sc );
    } else if ((key.readyOps() & SelectionKey.OP_READ)
    == SelectionKey.OP_READ) {
    // Read the data
    SocketChannel sc = (SocketChannel)key.channel();
    // Echo data
    in.clear();
    sc.read( in ); // <--------------------- this is where it stops
    in.flip();
    char command = in.getChar();
    if (command == 'l')
    CharBuffer cb = in.asCharBuffer();
    String Username = getString(cb);
    String Password = getString(cb);
    System.out.println("Login Attempt: User: " + Username + " Pass: " + Password);
    it.remove();
    for the client side i have tried almost every thing. I had similar trouble when I used Streams originaly, but the problem was that I had forgotten to flush the stream. I have tried using streams to communicate with the channel, or even getting the socket from the client socketchannel and then fluching its outputstream. and neither worked, even though I saw this in a tutorial somewhere online.
    Alas, I am completely out of ideas and extremely frustrated at the days of time lost on this upgrade that would have made for better performance had it actually performed. I you can think of what kind of client side code woul dbe necessaryto make this work, please let me know. I have tried simply making a channel, connecting it, filling a buffer (which works), and doing clientChannel.write(buf). No, this odes not work. EVERY tutorial says this is how to do it, but I'm special some how.
    HELP ME!!!
    Jon

    Never release your socketChannel reference(s) unless it/they has/have been fully qualified
    by socketChannel.isRegistered();
    Otherwise you can wipe out your iterator by having the references garbage collected
    before they have actually been freed.
    In the event of an exception on the channel, before releasing the reference
    call socketChannel.isRegistered(). It may take some time to qualify and thus
    I make a list of channels that have had exceptions such as the user disconnecting
    and poll socketChannel.isRegistered() every so often untill it qualifies,
    Then and only then release the reference to the channel.
    I went even one further.. I interleave the OP_READ and OP_WRITES in different
    properly synchronized Threads, and never combine the options on the same Selector
    at the same time. Further always using a timeout on my selector ensures
    it won't race for(;;) and or get saturated.
    I ran my NIO server for 6+ months straight no problems and have tested it to 7200+ concurrent connections. Actually I am almost at the point where other people can use it via an easy interface.
    Hmm if I could just find time to finish between my job and woman :)
    I am going to work onit as much as I can this weekend and I am making it totally
    configurable and usable from an easy GUI.
    Anyway, check where you remove your channel references
    Hope this helps.
    (T)

  • How to read from and write into the same file from multiple threads?

    I need to read from and write into a same file multiple threads.
    How can we do that without any data contamination.
    Can u please provide coding for this type of task.
    Thanks in advance.

    Assuming you are using RandomAccessFile, you can use the locking functionality in the Java NIO library to lock sections of a file that you are reading/writing from each thread (or process).
    If you can't use NIO, and all your threads are in the same application, you can create your own in-process locking mechanism that each thread uses prior to accessing the file. That would take some development, and the OS already has the capability, so using NIO is the best way to go if you can use JDK 1.4 or higher.
    - K
    I need to read from and write into a same file
    multiple threads.
    How can we do that without any data contamination.
    Can u please provide coding for this type of task.
    Thanks in advance.

  • Sharing socket object between threads - Is any sync required?

    For example, a thread receives (listens) datagram packets at incoming socket and forwards them downstream through another datagram socket. Another thread listens packets at this second socket and forwards the data via the first socket. It is possible that two threads invoke methods of the same socket (one is receiveng while another is sending). This situation is not described in the DatagramSocket manual. I beleive there is underlying synchronization at the OS kernel level. Can I relay on it? Thanks.

    I expected some critics for using old plain sockets instead of nio :)You should use NIO if you have hundreds of connections. If you have a small number of connections and want a simple implementation use blocking IO as you have.
    If you can have different
    threads reading or writing at once eg two readingor
    two writing then you need to use synchronisation.Shouldn't this be stated by the API designers somewhere?It is probibly covered in a tutorial or example somewhere.
    You have a different input and output stream. There is a lock on each. This is your best hint.
    Theoretically, nothing prohibits sending UDP packets in race conditions.
    In fact, this is what my program
    does - it respondes to different clients using one
    (server) datagram socket. The responses are produced
    by multiple threads. I suppose that java does not
    involve any state variables; thus, beleive that the
    system can accomplish the synchronisation unnecesary
    at the application level.That depends on how you build and send your messages. If each part of the message can be sent in one hit and the order does not matter you are fine.
    If you have a single object shared between threads, then all members are shared, not just static variables.

  • Server socket programming and thread

    hello,
    briefly this is what i have sought out to do : the server waits for the client indefinitely,upon a client requesting for service by writing a service id into the socket, a new thread of the type id as read by the server which is a sub-class of the Server (main-class) is exec'd.
    the problem as i understand is that the client can send as much of data as it desires to the server and the thread can read the data it receives by the clients.the server(thread) fails to write reply to the client;eventhough out.write() is successful;the client is blocked in read() indefinitely.is it because of the thread which runs at a different port the client does not know and the server is not redirecting response to the client.
    how do i read what the server(thread) writes onto the socket from the clients.

    thanks again,just check out this code please
    public class Server extends Thread //create a multi-threaded server
        /* *Creates a new instance of Server  */
        String                           serverAddr=CodeServer.ServerRun.SERVER_IP_ADDR;
        int                              serverPortNum=CodeServer.ServerRun.SERVER_TCP_PORT;   
        ServerSocket                     sSock;
        Socket                           cSocket;
        int                              requestID=0;
        boolean                          debug=true;  
        InputStream                      in =null;
        OutputStream                     out=null;
        Server ()
        Server (Socket csocket)
            this.cSocket = csocket;
        /* start the server at specifed portNum */
        private void initialise ()
            try
                //start the server at serverPortNum
                sSock=new ServerSocket (serverPortNum);
            catch (IOException ex)
                ex.printStackTrace ();
            /* console output of status of server */
            if(debug==true)
                System.out.println ("Server waiting @ "+sSock);
        private void acceptRequest ()
            try
                this.cSocket=sSock.accept ();
                if(debug==true)
                    System.out.println ("client socket @ "+cSocket);
            catch (IOException ex)
                ex.printStackTrace ();
        private void readRequestID ()
            /*step 1: determine the type of server before threading
             *a request the the type of server got by the request ID
             * number */       
            try
                in        =cSocket.getInputStream ();
                requestID =in.read ();
                out       =cSocket.getOutputStream ();
                if(debug==true)
                    System.out.println ("accross the client:"+requestID);
            catch (IOException ex)
                ex.printStackTrace ();
        private void execThreadForRequest ()
            /*step 2: after requestID is received on the socket.
             *its time to decide the server to thread the control into.
            switch(requestID)
                case 1: //invoke the RegisterServer thread
                    new CodeServer.Core.RegistrationServer (this.cSocket).start ();
                    break;
                case 2: //invoke the ListingServer thread
                    break;
                case 3: //invoke the MessageTransferServer thread
                    break;
                case 4: //invoke the CallSetupServer thread
                    break;
                case 5: //invoke the DisconnectServer thread
                    break;
                case 6: //invoke the ChangeUserStatusServer thread
                    break;
        public void run ()
            // client processing code here==super class does nothing here
        public static void main (String args[]) throws Exception
            Server s=new Server ();
            s.initialise ();
            /* start indefinitely the main server thread */
            while (true)
               /* accept() blocks the server for a request
                  a new request is put into a thread for processing */
                s.acceptRequest (); //initialise the clientSocket
                s.readRequestID (); //get the actual requested service
                s.execThreadForRequest (); //start the actual server thread
    /**registration service class;
    *registers the IP address of the caller,callee and the status
    *adds the caller to the hash table and updates status
    class RegistrationServer extends Server
        Socket              cSocket;
        InetAddress         clientAddr;
        DataInputStream     inStream;
        DataOutputStream    outStream;
        //Socket s=new Socket()
        RegistrationServer (Socket cSocket)
            this.cSocket=cSocket;
            clientAddr =cSocket.getInetAddress ();
            try
                //init for reading status and custom message.
                inStream     =new DataInputStream (cSocket.getInputStream ());
                outStream    =new DataOutputStream (cSocket.getOutputStream ());
            catch (IOException ex)
                ex.printStackTrace ();
            if(CodeServer.ROO.DEBUG==true)
                System.out.println ("register server:"+cSocket
                                   +" host ip:"+clientAddr.getHostName ());
        public void run ()
            int    status=0;
            String custMesg=null;
            try
                /* read the custom message */
                if(inStream.available ()>0)
                    try
                        custMesg=inStream.readUTF ();
                        System.out.println (""+custMesg);
                    catch(EOFException e)
                        e.printStackTrace ();
                else
                    custMesg="";
            catch (IOException ex)
                ex.printStackTrace ();
                try
                           here is the problem, i found if i try reading accross the client             
                           i only receive a junk value 81 always */
                       outStream.write(1); //write success
                        outStream.flush();
                catch (IOException ex)
                    ex.printStackTrace ();
    }and with the client GUI :thanks for the help.please do find time to help me out with a suggestion or two on this code.

  • Goods Issue against outbound delivery from blocked stock

    Dear All
    I want to do goods issue against outbound delivery created without any reference from blocked stock of my storage location. Is there any way I can achieve this? I know normally SAP allows goods issue from unrestricted stock but my business scenario requires goods issue to be done from blocked stock against outbound delivery.
    Please let me know any solution for this.
    Thanks and Regards
    Satish Kumar

    Hi
    Check this link where similar issue has discussed and its resolved as well. Please try this and update the findings. If possible could you share the background of this strange requirement.
    http://scn.sap.com/thread/1541911
    Thank$

  • Can i write to a DatagramChannel from 2 threads?

    Without using a Selector - i wanna give one thread an option to read from the channel and right after that - to write, and give another thread that receives the channel as parameter
    the option to write whenever it needs (a condition i'm using).
    The API says "Datagram channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at
    most one thread may be writing at any given time." - can i rely on that?
    Thanks,
    Snayit

    This works fine for other Channel types but I haven't tried DatagramChannel

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • Anybody having problems in Mail when sending reply messages from a thread and the message is not showing in the Sent mailbox?

    Hello Folks;
    Got a weird one...
    I am sending replies from a thread in Mail and they seem to have been sent (sounds) but they don't show in the Sent mailbox... O-0 These messages seem to have been delivered to cyberspace as they don't show in my Sent mailbox on my IMAP server... This has been happening for the last month... I have checked and verified all of my IMAP settings and Mailbox behavior settings... This is really weird and maybe a bug.... I checked all of my other clients that have access to the server on the same account and these messages do not show there either.... Any ideas?
    --prd54usa

    The messages are getting to the recipient...
    I am on a Comcast IMAP server if this has anything to do with it and the server settings are following the correct server port numbers, SSL settings, etc... I save Sent messages on the IMAP server for 90 days.... None of these "disappearing" messages were on the server for more than a couple of days.. Typically, these messages will get 'hung' in the Outgoing Mailbox for @30 seconds before sending... like they are being scanned for viruses or Mail can't connect to the server all of a sudden...
    I anybody else here is on a Comcast IMAP server, and having this problem of disappearing Sent messages... This would tell us that it might be a Mail Provider issue with their outgoing server...
    --prd54usa

  • Help! how to refresh the JTable of a class from another thread class

    there is an application, in server side ,there are two classes, one is a class called face class that screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much

    thank you very much !
    i tried it ,but the TableModel i used like this ,and how to change the TableModel?
    here the files of mine ,pls give me some help,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write?? }
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

  • Accessing object of the main class from the thread

    Hi, I'm having problem accessing object of the main class from the thread. I have only one Thread and I'm calling log.append() from the Thread. Object log is defined and inicialized in the main class like this:
    public Text log;  // Text is SWT component
    log = new Text(...);Here is a Thread code:
    ...while((line = br.readLine())!=null) {
         try {
              log.append(line + "\r\n");
         } catch (SWTException swte) {
              ErrorMsg("SWT error: "+swte.getMessage());
    }Error is: org.eclipse.swt.SWTException: Invalid thread access
    When I replace log.append(...) with System.out.println(..) it works just fine, so my question is do the log.append(..) the right way.

    This is NOT a Java problem but a SWT specific issue.
    It is listed on the SWT FAQ page http://www.eclipse.org/swt/faq.php#uithread
    For more help with this you need to ask your question on a SWT specific forum, there is not a thing in these forums. This advice isn't just about SWT by the way but for all specific API exceptions/problems. You should take those questions to the forum or mailing list for that API. This forum is for general problems and exceptions arising from using the "core" Java libraries.

Maybe you are looking for