Java Network Programming with Callback model

原创 2015年07月10日 09:47:49

Below codes use threads to merge files with callback model.

  1. Merge process : CallbackMain
package org.mantis.test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CallbackMain {
    private static String FILEPATH = "C:/Users/jb48021/Workspace/OscarFrontEnd/TestApp/Thrift/properties/logFilesReceived1.txt";
    private static BufferedWriter FILEOUTPUT;
    private static int THREADSNO;
    private static int COUNTER = 0;
    private static boolean[] THREADFLAGS;

    static {
        try {
            FILEOUTPUT = new BufferedWriter(new FileWriter(FILEPATH));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public CallbackMain() {
    }

    public static void WriteLog(List<String> listParam) throws IOException,
            InterruptedException {
        synchronized (FILEOUTPUT) {
            while (!listParam.isEmpty()) {
                FILEOUTPUT.write(listParam.remove(0));
                FILEOUTPUT.newLine();
                COUNTER++;
            }
            FILEOUTPUT.flush();
        }
        // System.out.println("Main COUNTER : " + COUNTER);
    }

    public static void updateFlag(boolean flag, int id) {
        synchronized (THREADFLAGS) {
            THREADFLAGS[id] = flag;
        }
    }

    public String charToString(char[] buffer) {
        if (buffer == null)
            return "";

        StringBuffer string = new StringBuffer(66);
        for (char c : buffer) {
            // System.out.print(c);
            string.append(c);
        }
        return string.toString();
    }

    public static String getFILEPATH() {
        return FILEPATH;
    }

    public static void setFILEPATH(String fILEPATH) {
        FILEPATH = fILEPATH;
    }

    public static BufferedWriter getFILEOUTPUT() {
        return FILEOUTPUT;
    }

    public static void setFILEOUTPUT(BufferedWriter fILEOUTPUT) {
        FILEOUTPUT = fILEOUTPUT;
    }

    public static int getCOUNTER() {
        return COUNTER;
    }

    public static void setCOUNTER(int cOUNTER) {
        COUNTER = cOUNTER;
    }

    public static int getTHREADSNO() {
        return THREADSNO;
    }

    public static void setTHREADSNO(int tHREADSNO) {
        THREADSNO = tHREADSNO;
        THREADFLAGS = new boolean[THREADSNO];
        while(tHREADSNO-- > 0){
            THREADFLAGS[tHREADSNO] = false;
        }
    }

    public static boolean[] getTHREADFLAGS() {
        return THREADFLAGS;
    }
}
  1. Files reader thread : CallbackThread
package org.mantis.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CallbackThread implements Runnable {
    private String filePath;
    private List<String> buffer1 = new ArrayList<String>();
    private List<String> buffer2 = new ArrayList<String>();
    private BufferedReader fileInput;
    private int counter = 0;
    private int threadID = 0;
    private String inputBuffer;
    private boolean endFlag = false;
    private static int MAXLINE = 10;

    public CallbackThread() {
    }

    public CallbackThread(int id) {
        this.threadID = id;
        filePath = "C:/Users/jb48021/Workspace/OscarFrontEnd/TestApp/Thrift/properties/logFiles"
                + id + "Received.txt";
        try {
            fileInput = new BufferedReader(new FileReader(new File(filePath)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void putListFromFile(int i) throws IOException, InterruptedException {
        while (i < MAXLINE) {
            if ((inputBuffer = fileInput.readLine()) != null) {
                buffer1.add(i++, inputBuffer);
            } else {
                endFlag = true;
                break;
            }
        }
        counter += i;
       CallbackMain.WriteLog(buffer1);
    }

    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        while (!endFlag) {
            try {
                putListFromFile(0);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            CallbackMain.updateFlag(true, threadID);
            fileInput.close();
            boolean[] flag = CallbackMain.getTHREADFLAGS();
            int i = CallbackMain.getTHREADSNO();
            if (i-- > 0)
                while (flag[i--])
                    if(i < 0) {
                        CallbackMain.getFILEOUTPUT().close();
                        System.out.println(Thread.currentThread().getName() + " closed main outPut stream!");
                        break;
                    }
        } catch (IOException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();

        System.out.println("Thread " + Thread.currentThread().getName()
                + " comes to end, processed " + counter + " records, used "
                + (endTime - startTime) + " millis...");
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    public int getThreadID() {
        return threadID;
    }

    public void setThreadID(int threadID) {
        this.threadID = threadID;
    }
}
  1. UnitTest
package org.mantis.test;

import java.io.IOException;

public class UnitTest {

    public static void callbackInterface() {
        Thread t = null;
        CallbackThread cThread = null;
        int MAXTHREADS = 3;
        CallbackMain.setTHREADSNO(MAXTHREADS);

        int id;
        for (id = 0; id < MAXTHREADS;) {
            cThread = new CallbackThread(id);
            t = new Thread(cThread);
            t.setName("thread" + id++);
            t.start();
        }

    }
    public static void main(String[] args) { 
         UnitTest.callbackInterface(); 
    }
}
  1. result:
    Thread thread1 comes to end, processed 51 records, used 7 millis…
    Thread thread2 comes to end, processed 3403 records, used 84 millis…
    thread0 closed main outPut stream!
    Thread thread0 comes to end, processed 12546 records, used 115 millis…

Network Programming for Microsoft Windows 2nd(Windows 网络编程第二版) 学习心得

Winsock 头文件和所要求链接的库1.winsock2.h Ws2_32.lib  (Winsock 2)2.winsock.h wsock32.lib  (Winsock 1, Windows ...
  • exy337
  • exy337
  • 2010年10月26日 10:02
  • 2269

java Network programming using socket(1)

Java supports stream-based communication and packet-based communication,and the first is universal. ...
  • qq_16912257
  • qq_16912257
  • 2015年05月24日 09:51
  • 886

Unix network programming

1.部署环境。这个就不用写了   参考  http://blog.csdn.net/hantangsongming/article/details/20453349 已经写的很好了。   ...
  • huohunri2013
  • huohunri2013
  • 2015年01月18日 17:32
  • 784

Unix Network Programming(1)---基本概念说法

一个简单的时间获取函数#include 'unp' //包含自己编写的头文件,该头文件包含大多数网络程序都需要的许多系统头文件, 并定义了所用到的各种常值 i...
  • liyuan_35023
  • liyuan_35023
  • 2015年10月16日 21:06
  • 430

Beej's Guide to Network Programming 学习笔记

Beej's Guide to Network Programming
  • harryhare
  • harryhare
  • 2014年04月20日 02:12
  • 1790

《The Definitive Guide to Linux Network Programming》 (《Linux 网络编程指南》) Chapter 2

第二章 函数
  • ahaahajsh
  • ahaahajsh
  • 2014年06月23日 14:11
  • 557

Boost.Asio C++ Network Programming翻译的校对稿

Boost.Asio C++ Network Programming翻译的校对稿将发布在gitbook上:https://www.gitbook.com/book/mmoaay/boost-asio-...
  • mmoaay
  • mmoaay
  • 2014年12月25日 09:05
  • 3547

Professional iOS Network Programming翻译第一章:iOS网络功能简介

小引 在iOS开发中,网络是非常重要的功能,针对iOS开发者来说,掌握好iOS中网络功能的开发也是必不可少的。最近在看一本书:Professional iOS Network Program...
  • cui7230102
  • cui7230102
  • 2013年11月05日 11:44
  • 1048

twisted network programming essentials 读书体会

首先twisted是在python结构下的一个事件驱动的网络框架。你可以在此基础上做出遵循各种协议的client--server结构的软件应用. 刚刚读了第一大章 An Intrduction to ...
  • wangeen
  • wangeen
  • 2014年09月28日 17:06
  • 1375

Linux Network Programming Intro - Dual Network Card

1.  对于双网卡, 一个网卡绑定IP 192.168.1.189 另一个绑定192.168.3.161 2. 监听应用服务程序在 192.168.1.189 地址上监听 3. ...
  • fanbird2008
  • fanbird2008
  • 2015年10月08日 14:22
  • 263
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java Network Programming with Callback model
举报原因:
原因补充:

(最多只允许输入30个字)