简体   繁体   中英

Multithreading with TCP / IP socket

I am working on sockets in Java. The thing is we are acquiring signal from hardware device and if the device is not scanned after certain interval (200ms) is hangs. So I need to speed up this operation. How can I use multitasking to speed up the following code.

The no of rows here is usually in the range of 250.

    sock = new Socket("localhost", def.PORT);

    OutputStream outStream = sock.getOutputStream();
    DataOutputStream outDataStream = new DataOutputStream(outStream);
    /**************** Start Command for CystometryEMG *****************/
    outDataStream.writeInt(size);
    outDataStream.writeInt(command);
    outDataStream.writeBytes(msg);

    InputStream input = new BufferedInputStream(sock.getInputStream());
    reader = new DataInputStream(input);

    sock.setSoTimeout(def.SOCKET_READ_TIME_OUT);
    if (sock.isClosed())
        return;
    size = reader.readInt();
    command = reader.readInt();
    errorCode = reader.readInt();
    NoofCols = reader.readInt();
    NoOfRows = reader.readInt();

    /************** Now get the input from the device *************/

    for (int i = 0; i < NoOfRows; i++)
        arrPb[i] = reader.readDouble();

    for (int i = 0; i < NoOfRows; i++)
        arrPv[i] = reader.readDouble();

    for (int i = 0; i < NoOfRows; i++)
        arrV[i] = reader.readDouble();

    for (int i = 0; i < NoOfRows; i++)
        arrVn[i] = reader.readDouble();

    sock.close();

Decouple scanning the device from all other operations. Split this into two threads. One thread (frontend) handles nothing but scanning the device and saving the data received into a queue. This thread should run with maximum priority. The second thread (backend) takes data from the queue and does whatever you want with it, at leisure. You will probably need multiple backend threads, and after you get this working you'll need to tune the number of backend threads to ensure that you can process requests faster than they're received from the device, otherwise your queue will grow too large.

Note however that Java is generally not a realtime language and even with a dedicated thread it may be possible for the frontend thread to take more time to get scheduled that you might like. You might do a web search for "realtime java" to see if any of the existing realtime JVMs out there can help you.

Regardless, don't even think about running this on anything less than a 4-core CPU

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM