开发者

Avoid garbage collection when using sockets

In a game project of mine i'm trying my best to avoid the creation of objects and thus preventing the garbage collector from running.

It is a network game and I am mostly sending byte arrays of data but also some other objects like int arrays.

I have noticed when analyzing the memory allocation in eclipse that there are alot of byte arrays created in my program by the way I'm writing/reading to/from the sockets.

oos=new ObjectOutputStream(new BufferedOutputStream(link.getOutputStream()));
ois=new ObjectInputStream(new BufferedInputStream(link.getInputStream()));

How can I read / write (mostly byte arrays) from / to sockets without creating any more objects in the background?

Also what would be the fastest way to do this network communication? I need to squeez every bit of performance out of this application.

EDIT

I have changed my code a bit and i now only send loose bytes and ints through the oos. Still there is allocations done.

Allocations screenshot

Reading code

@Override
public void run() {
    super.run();
    byte packet = -1;
    while(connected){
        try {
            packet = ois.readByte();
            handlePacket(packet);
        } catch (OptionalDataException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            connected=false;
        }
    }

}

@Override
public void handlePacket(byte b) throws OptionalDataException, ClassNotFoundException, IOException {
    super.handlePacket(b);
    //TODO add more packets 
    switch(b){
    case Packet.SERVER_SEND_PLAYER_LOCATIONS:
        this.locations=(int[]) ois.readObject();
        break;
    case Packet.SERVER_SEND_PLAYER_COLORS:
        this.colors= (int[]) ois.readObject();
        break;
    case Packet.SERVER_SEND_WORM_WIDTH:
        wormWidth = ois.read();
        brea开发者_开发知识库k;
    case Packet.SERVER_SEND_PLAYER_NUMBER:
        numberOfPlayers = ois.read();
        break;
    case Packet.CS_SEND_TURN:
        gp.addTurn(ois.read(),ois.read(),ois.readByte());
        break;
    }
}

Writing

    public void send(byte value){
    try {
        oos.write(value);
        oos.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public void send(int value){
    try {
        oos.write(value);
        oos.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


just make sure there's no references to those arrays !!!

some of your code will help

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜