Is PLSQL support multi thread mechanism?

hi
i am tring to simulate my problem here. just go thru and bestow a good solution.
consider, i have table called "table_a" which contains around 10 records. for each record having 100 'levels of status infromation' which stored in another table called "table_b". i want to combine(outer join,) this two table and populated into another table called "table_c". since i am doing a outer join i will get 100 record for eche single record presented in "table_a". so totally table_c will cantain 1000 record after insertion.
this transformation involving lot of complex calculation for each record present in "table_a", to do this i have a separate procedure it will take a each record from "table_a" , outer join with table_b and will do all the complex calculation then insert into the table_c. so i have to follow the same process for all the 10 record presented in the table_a.
for inserting the 10 record information (table_a) into table_c , i have to call the same procedure 10 time. consider each call will take 30 minutes to complete. then totally this insertion will table 300 minutes.
so is there any way to insert these 10 record Parallely using plsql?.
just for example i have explained with 10 records, here actual number is huge.
Thanks
Kalanidhi

If you can move all the logic into SQL, then it's relatively easy to let Oracle handle the parallelism via parallel DML. That is going to be the most efficient solution.
If you cannot put the logic into SQL and have to have PL/SQL, you can run multiple sessions in parallel using the DBMS_JOB or DBMS_SCHEDULER package each handling a different subset of the data. But that probably implies writing the code to distribute the work as well as writing code to monitor those other sessions to determine when they're done.
A third potential option would be to build parallelizable pipelined table functions and letting Oracle do parallel DML with those.
Justin

Similar Messages

  • Analysis for Office support multi thread?

    Does Analysis for Office support multi thread/core? If so, what verison? I tried searching around this site as well as note 1466118 - Hardware & Software requirements for Analysis, edition for MS Office but was unable to find an answer.
    I am on an Intel dual cpu with hyper threading turned on so it essentially looks like 4 cores. When I execute an Analysis View, I rarely see the EXCEL.EXE process go above 25% CPU utilization. I have plenty of RAM and hard drive space.
    64bit Windows 7
    32bit Office 2010
    AAO 1.3.5.2288
    Thanks

    I found the following info at:
    Excel 2010 Performance: Performance and Limit Improvements
    Large Data Sets and 64-bit Excel
    The 64-bit version of Excel 2010 is not constrained to 2 GB of RAM like 32-bit applications. Therefore, 64-bit Excel 2010 enables users to create much larger workbooks. 64-bit Windows enables a larger addressable memory capacity, and 64-bit Excel is designed to take advantage of that capacity. For example, users are able to fill more of the grid with data than was possible in previous versions of Excel. As more RAM is added to the computer, Excel uses that additional memory, allows larger and larger workbooks, and scales with the amount of RAM available.
    In addition, because 64-bit Excel enables larger data sets, both 32-bit and 64-bit Excel 2010 introduce improvements to common large data set tasks such as entering and filling down data, sorting, filtering, and copying and pasting data. Memory usage is also optimized to be more efficient, in both the 32-bit and 64-bit versions of Excel.
    Multi-Core Processing
    Additional investments were made to take advantage of multi-core processors and increase performance for routine tasks. Starting in Excel 2010, the following features use multi-core processors: saving a file, opening a file, refreshing a PivotTable (for external data sources, except OLAP and SharePoint), sorting a cell table, sorting a PivotTable, and auto-sizing a column.
    For operations that involve reading and loading or writing data, such as opening a file, saving a file or refreshing data, splitting the operation into two processes increases performance speed. The first process gets the data, and the second process loads the data into the appropriate structure in memory or writes the data to a file. In this way, as soon as the first process beings reading a portion of data, the second process can immediately start loading or writing that data, while the first process continues to read the next portion of data. Previously, the first process had to finish reading all the data in a certain section before the second process could load that section of the data into memory or write the data to a file.

  • Does RMI supports multi threading?

    Hi, Does RMI supports Multi threading or not? What is the disadvantage of RMI and why EJB came?
    Thanks in advance
    By
    vinod

    (a) yes
    (b) firewall penetration is its biggest problem
    (c) EJB is built over RMI, don't get the wrong idea about that. It's a large topic - search as recommended, especially for the Sun White Papers

  • How should implement multi-thread in single-threaded Operating system using

    How should implement multi-thread in single-threaded Operating system using java?
    Java supports "Multi-threading".Is there is any way run the multiple threads (Implementing multi threading) using java in a Single-threaded Operating system (That is the operating system does not support for multi-threading).

    Previous questions from OP suggest they are using J2ME, so the question might be possible.
    806437 wrote:
    How should implement multi-thread in single-threaded Operating system using java?
    What is the actual question/problem?
    A java app doesn't do threads or not do threads. It uses classes. The VM does threads.
    So if you have a platform that does not have threads and you want to support the thread class then the VM, not a java app, must provide some pseudo mechanism, such as green threads, to support that.
    If your question is about java code and not the VM then you must build a task engine and insure that the tasks are of short enough duration that it is an effective use for your system.

  • Indesign and multi threaded cpu support??????????

    When the indesign will finally support multi-core processors?????? It is tragic that adobe dont have any support for multi-core cpu and that this products cost thousends $$$$$!!!!!!!!!!!!!!! Only premiere and some photoshop function support multi-core cpu.

    If you are good freelancer you can get money spent on CS back in a month. So I would not call this software expensive. What concerns multi threaded cpu support I believe that programming tools as well as operating systems need to evolve. I am sure that we will get better support in this matter in close future.

  • Acrobat X multi threaded cpu support??????????

    When the acrobat family will finally support multi-core processors (acrobat, distiller...)?????? It is tragic that adobe dont have any support for multi-core cpu and that this products cost thousends $$$$$!!!!!!!!!!!!!!! Only premiere and some photoshop function support multi-core cpu.

    I agree. This is mad. It's 2011 and still no multi-core support. I have a requirement to OCR scanned PDF documents. I get about 100,000 PDFs per month. I hate looking at my Resource Manager and only seeing 1 out of 24 cores being used. What a waste!!!!
    What are you doing about this adobe? It's 2011 and your software is so far behind in this area. Am I missing something. Is there another tool you have that I just don't know about?

  • Multi-Threaded FTP

    Multi-Threaded FTP was a huge attraction for me, and one of the features that sold me on upgrading to Dreamweaver CS6.  However, I haven't seen any sign of it in the product or any documentation to help me use it.  My files keep transferring in the traditional one-at-a-time way.
    Is there something I need to do to enable this feature? Has anybody used this feature yet?

    Might not help but I saw this in the comments on David Powers' blog
    http://foundationphp.com/blog/2012/04/23/my-verdict-on-dreamweaver-cs6/
    "Multi-thread FTP is the default in Dreamweaver CS6. You can neither turn it on nor off. It handles a maximum of three transfers simultaneously in either direction (so you can download at the same time as uploading). However, it doesn’t work with Check In/Check Out."
    He also has the following comments in the body of the blog entry:
    Multichannel FTP
    Let’s be honest. In the past, Dreamweaver’s FTP client was a dog. Not any more. It now supports multichannel transfers, and can even download at the same time as uploading. Orange arrows indicate items queued for transfer. When the transfer begins, the arrow turns green. And if you’re transferring a large item, hovering over the filename displays a tooltip of how much of the file has been transferred. With Dreamweaver CS5.5, it took more than 90 minutes to  upload a WordPress site on my internet connection. Now, it’s more than ten times faster.
    The FTP error messages are also more meaningful. No one is likely to buy Dreamweaver CS6 for its FTP client alone, but this is a major improvement to the program.

  • I have problem using ObjectOutputStream with Multi-Thread

    I am writing a network rpg game for the project.
    Because it is a network game, so i use thread to support multi-user.
    When i using the string to store the command, and send to the server,
    it still can work. You can downlod at http://ivebug.tripod.com/new-string.zip
    (You cannot click the link, you must use [save target as] to save the file)
    1. First compile the files then "java ChatServer",
    2. Then you can execute "java ChatClient".
    3. Input the name for username in the textfield and then press 'login button'.
    4. A small square appear in the up-left corner.
    5. Then you can click in the black panel to move the square.
    6. If you want more than one square can be move, go step 2 to step 5 again.
    It seems everthing is work, but i want more extention for future.
    So i change to use object to encapsulate the command.
    However, it can't work. It stops working after create the socket and
    it can can't run to the line to create an ObjectInputStream and ObjectOutputStream. I don't know why. Who can tell me.
    The program using object at http://ivebug.tripod.com/new-object.zip
    (You cannot click the link, you must use [save target as] to save the file)

    Thank you for solve my problem.
    Now, i can send the object though the socket, however new problem occurs.
    The problem is that after i sent the 'login' object to server,
    the client lost the connection.
    The program has lost connection problem : http://ivebug.tripod.com/new-lost.zip

  • Multi-threading in Flash Builder 4.6

    Hello All,
    I am a new user of Flex and Flash Builder 4.6.
    Is there any built-in mechanism that allows to implement multi-threading in Flex/Flash Builder 4.6?
    I have done a little research via the Internet regarding this issue, and I understand that there are ways to implement multi-threading, but I am interested in a built in mechanism.
    Thanks in advance,
    Felix.
    P.S. Some links regarding this issue:
    http://cookbooks.adobe.com/post_Is_multi_threading_possible_in_Flash_or_ActionScri-12026.h tml
    http://www.flexjunk.com/2009/01/15/multi-threading-in-flexair/
    http://blogs.infosupport.com/flex-4-a-multi-threading-solution/

    Wokrers has been just announced today:
    http://www.bytearray.org/?p=3705
    Be patient around 3 more months and it will be out of the box.
    C

  • Is a Trigger Multi Thread?

    I’m trying to execute a SELECT statement WHERE status = X to make some operations when I insert a row in my Table.
    If there is another insert until is execute the firs insert, the Trigger is executed in other Thread or waits until the first ended?
    Is a Trigger Multi Thread?
    If is multi thread, is possible to make it in single thread or wait until the first one end?

    Each session will execute its own copy of the trigger.
    To single thread access to rows within a table look at the select for update statement.
    When designing transactions give thought to Oracle's read consistency model: readers will not wait on updaters to see the row contents.
    But by selecting for update you will cause other sessions that want to update the same selected row as taken by the first session to wait for the first session to commit or rollback before the second session performs its update.
    If you need to single thread access to the entire table you could be designing an applciation that will not scale to support multiple session access.
    HTH -- Mark D Powell --

  • MUlti-threading concept

    Hi All,
    Want to know how we can multi-thread a program for a particular PLSQL code in Oracle EBS for which the child thread doesn't consume any thread in the front-end even though it executes with user-specified threads?

    Hi;
    Please review below notes which could gives you some idea:
    How Does iPayment Use Multi Threading? [ID 983478.1]
    http://orabiz.blogspot.com/2010/06/ebs-plsql-multithreading-example.html
    Can I have multi-thread program in EBS
    Regard
    Helios

  • Multi-threaded agent not being used

    Solaris 9, Oracle 9.2.0.1
    The docs say the multi-threaded agent avoids processes starting every time a user opens a database connection. Except it doesn't seem to.
    I've started up the agent;
    ps -ef |grep hsodbc
    oracle 6193 1 0 14:21:07 ? 0:00 hsodbcMYSQL_R -mt
    But, when I establish 2 user connections across a database link, I see this;
    ps -ef |grep hsodbc
    oracle 6201 1 0 14:21:40 ? 0:00 hsodbcMYSQL_R (LOCAL=NO)
    oracle 6216 1 1 14:23:08 ? 0:00 hsodbcMYSQL_L (LOCAL=NO)
    oracle 6193 1 0 14:21:07 ? 0:00 hsodbcMYSQL_R -mt
    The multi-threaded agent isn't picking up and processing the connections as I would expect. Processes are being spawned in exactly the same way as when the mt agent is not running.
    I have checked the listener logs and the agent is registering ok at startup [and every 10 secs too!!!].
    Can anyone shed any light on why I am not seeing the benefits of the mt agent?
    TIA
    Steve

    Steve,
    MTA is not supported with Generic Connectivity.

  • Acrobat X Multi-Threaded?

    If I scan a document that has 100 pages and Adobe has to perform OCR and all of its other processing tasks, where can I tell it to do more than one page at a time??? I have 12 cores and Adobe barely uses 5% while doing this task which takes forever. This can absolutely be done in parallel in separate threads. Is there a setting in Adobe where I can say "Yes, use X cores when doing processor intensive tasks that can easily be run in parallel"

    I am not surprised. Thanks for the quick reply.
    If anyone from Adobe is listening, this one is a no brainer. Especially for people who archive all of their docs as they come in regularly. Multi-cores have been around for years. I think it would have been appropriate in X to support more threading in at least very basic areas.

  • What is multi threading?

    Hi all,
    What is multi threading? How to implement multi threading in ABAP?
    Regards,
    Bryan

    Hi
    How the vision connector framework works
    The connector interacts with an SAP application using connector modules. The connector modules make calls to SAP's Native Interfaces and pass data (business object or event data) to and from an SAP application. The connector's flexible design enables different modules to be used for different tasks such as initializing the connector with the SAP application or passing business object data.
    Communication between the connector and an SAP application
    The connector uses SAP's Remote Function Call (RFC) library to communicate with an SAP application. SAP's RFC API allows external programs to call ABAP function modules within an SAP application.
    Processing business objects
    The connector is metadata driven. Metadata, in the WebSphere business integration system, is application-specific data that is stored in business objects and that assists a connector module in its interaction with the application. A metadata-driven connector module handles each business object that it supports based on metadata encoded in the business object definition rather than on instructions hard-coded in the connector module.
    Business object metadata includes the structure of a business object, the settings of its attribute properties, and the content of its application-specific information. Because connector modules are metadata driven, they can handle new or modified business objects without requiring modifications to the connector-module code.
    The vision connector framework uses the value of the verb application-specific information in the top-level business object to call the appropriate connector module to process the business object. The verb application-specific information provides the classname of the connector module.
    The verb application-specific information of most top-level business objects must identify the classname of the connector module. The syntax of this verb application-specific information is:
    AppSpecificInfo = PartialPackageName.ClassName,
    For example,
    AppSpecificInfo = sap.sapextensionmodule.VSapBOHandler,
    In this example, sap.sapextensionmodule is the partial package name, and VSapBOHandler is the classname. The full package name includes the com.crossworlds.connectors prefix, which the WebSphere business integration system adds to the name automatically. In other words, the full text of the example is:
    com.crossworlds.connectors.sap.sapextensionmodule.VSapBOHandler
    Note:
    The verb application-specific information of most top-level business objects must use a comma (,) delimiter after the connector classname. However, the Server verb, which is used by the RFC Server Module, is delimited instead by a semi-colon (;). For information about the Server verb, see How the RFC Server Module works and Supported verbs.
    You need not specify the package name and classname for the verb application-specific information if the business object is used:
    by the ALE Module to process application events; however, when you use the ALE Module to process service call requests, you must specify the package name and classname
    by the ABAP Extension Module, which uses the default business object handler (sap.sapextensionmodule.VSapBOHandler)
    Important:
    Customer-generated connector modules that process business objects for the RFC Server Module must specify a full package name, which must begin with bapi. For example, bapi.client.Bapi_customer_getdetail2. The full package name in this example is bapi.client, and the classname is Bapi_customer_getdetail2.
    Most business object processing is specific to each connector module. By default the connector uses the ABAP Extension Module. For more information on business object processing for the ABAP Extension Module, see Installing and customizing the ABAP Extension Module and Business object data routing to ABAP handlers. .
    For more information on specifying verb application-specific information for the ALE Module, see Event processing and Processing multiple IDocs with a wrapper business object.
    Processing multiple concurrent interactions
    The Adapter Framework can create separate threads for processing an application event and a business object request. When processing multiple requests from the integration broker, it can create multiple threads to handle multiple business object requests. For example, when InterChange Server is the integration broker, the connector can receive multiple business object requests from multiple collaborations or from a multi-threaded collaboration.
    Figure 4 illustrates the multi-threading architecture.
    Figure 4. Multi-Threading Architecture of the Connector for SAP
    Event processing
    The connector performs the following steps when handling a poll call:
    The Adapter Framework creates a single dedicated thread to handle poll calls. This thread calls the pollForEvents() method of the vision connector framework at the frequency specified in the PollFrequency configuration property.
    The thread polls SAP, which uses a dialog process to locate and return the event.
    Note:
    If the connector's MaxNumberOfConnections configuration property evaluates to a number greater than 1, the vision connector framework dedicates a connection to SAP for polling. If MaxNumberOfConnections evaluates to 1, event and service-call request processing share a single connection to SAP.
    The polling thread dies only when the connector shuts down.
    Note:
    Because the RFC Server connector agent pushes events out of SAP instead of polling for events, it spawns its own threads instead of using threads created by the connector framework. Because the ALE connector agent uses the RFC Server connector agent to access events, it also spawns its own threads instead of using threads created by the connector framework when it processes events.
    Request processing
    Independently of polling, the Adapter Framework can create multiple request-processing threads, one for each request business object. Each request thread instantiates the appropriate business object handler.
    For example, when processing business object requests from InterChange Server, the number and type of business object handlers depends on the number and type of the collaborations sending the requests:
    If multiple collaborations send business objects, each request thread instantiates a business object handler of the appropriate type.
    If a multi-threaded collaboration sends multiple business objects of the same type, the request threads instantiate an equal number of business object handlers of that type.
    If the connector's MaxNumberOfConnections configuration property evaluates to a number greater than 1, the vision connector framework dedicates one connection to SAP for polling and allocates the remaining connections to a pool used only for request processing.
    As illustrated in Figure 4, the connector performs the following steps when handling a business object request:
    The Adapter Framework creates a separate thread for each business object request. Each thread calls the doVerbFor() method of the Vision business object handler.
    If the connector's MaxNumberOfConnections configuration property evaluates to a number greater than 1, the Vision business object handler checks the vision connector framework's connection pool to determine if a connection handle is available.
    If the handle is available, the thread sends the request to SAP, which uses a dialog process to handle the request.
    If the handle is not available, the thread waits until one becomes available. Thread sequencing determines the order in which each business object handler thread claims or waits for an available connection handle.
    If the connector's MaxNumberOfConnections configuration property evaluates to 1, the Vision business object handler shares a connection with event processing.
    SAP releases the dialog process after it completes processing and sends a return code.
    The connector releases the connection handle after it receives the return code from SAP.
    Setting the number of available connections
    Use the MaxNumberOfConnections configuration property to specify the maximum number of connection handles available. The number of connections cannot exceed the number of dialog processes.
    SAP locks the dialog process while processing an interaction, releasing it only when the interaction completes. Therefore, multiple concurrent requests lock an equal number of dialog processes until processing finishes.
    Important:
    Before setting a value for MaxNumberOfConnections, contact your SAP BASIS administrator to determine an appropriate value to maximize throughput without negatively affecting performance on the application server.
    Support for multiple connections
    By default the connector supports multiple-threads.
    <b>
    REWARD IF USEFULL</b>

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

Maybe you are looking for