Java read Level-1 quotes dbf File optimization (2), level-1dbf

Source: Internet
Author: User

Java read Level-1 quotes dbf File optimization (2), level-1dbf

Recently, a project was constructed to achieve market access and distribution, which requires extreme low latency. This is very important for the securities system. The access line source can be configured, either Level-1 or Level-2 or another third-party source. Although the Level-1 market is not as fast as Level-2, we still need to optimize it as the line source supported by the system so that the user can read the file and receive the quotation through socket, the end-to-end latency is as low as possible. This article describes the optimal solution for reading level-1 dbf Files. I believe that reading other dbf Files should also be of reference significance.

Level-1 market is a small market site. It regularly updates the dbf File (show2003.dbf in Shanghai and sjshq. dbf in Shenzhen) every few seconds and replaces the old one with the new market. Our goal is to read the file to the memory in the shortest time after the new file is updated, convert each row to an object, and convert each column to the corresponding data type.

We have adopted six optimization methods in total.

We introduced two optimization strategies in the above "Java reading Level-1 dbf File optimization (1:

Optimization 1: Use a memory hard disk (RamDisk) optimization 2: Use JNotify, replace round robin with notifications

 

This article continues:

Optimization 3: using NIO to read files

There are many open-source implementations for reading and writing Dbf Files. Selecting and improving them is an important strategy here.

 

Many Dbf libraries are implemented based on stream I/O, that is, InputStream and OutStream. We should adopt NIO, that is, based on RandomAccessFile, FileChannel and ByteBuffer. The stream is used to process data while reading data from the file. NIO can be used to load the entire file to the memory at a time. Tests show that (see Java program performance optimization) NIO is about five times faster than the stream method. Here I provide a database for reading dbf using NIO for you to download and learn (the original source is no longer available. This code has been rewritten, and it also includes the optimization policies that will be proposed later.) If your project already has a dbf library, we recommend that you improve it based on the optimization policies described in this article, instead of directly replacing it with what I provide.

DBFReader Library

 

DBFReader. java contains the following code snippet:

Code for creating a FileChannel:

this.dbf = new RandomAccessFile(file, "r");this.fc = dbf.getChannel();

 

The code for loading the specified file segment to ByteBuffer is

private ByteBuffer loadData(int offset, int length) throws IOException {        // return fc.map(MapMode.READ_ONLY, offset, length).load();        ByteBuffer b = ByteBuffer.allocateDirect(length);        fc.position(offset);        fc.read(b);        b.rewind();        return b;    }

 

Above, we use ByteBuffer. allocateDirect (length) to create ByteBuffer. The allocateDirect method creates DirectBuffer, and DirectBuffer is allocated in the "kernel cache zone", which is twice faster than the common ByteBuffer, which is also conducive to program optimization. However, the creation and destruction of DirectBuffer are time-consuming and will be solved in our next optimization.

(I am not going to introduce NIO-related knowledge in detail (or I may not be clear about it), or I am not going to introduce DbfReader in detail. java code focuses only on performance-related parts, and so on .)

 

Optimization 4: Reduce memory allocation and GC when reading files

The following are the basic steps for reading files from DBFReader. java files:

1. Read the entire file (except the file header) to ByteBuffer (actually DirectBuffer)

2. read each row from ByteBuffer to byte [] arrays.

3. encapsulate these byte [] arrays in a Record object (the Record object provides various methods to read columns from byte ).

See the following loadRecordsWithOutDel method:

private List<Record> loadRecordsWithOutDel() throws IOException {        ByteBuffer bb = loadData(getDataIndex(), getCount() * getRecordLength());        List<Record> rds = new ArrayList<Record>(getCount());        for (int i = 0; i < getCount(); i++) {            byte[] b = new byte[getRecordLength()];            bb.get(b);            if ((char) b[0] != '*') {                Record r = new Record(b);                rds.add(r);            }        }        bb.clear();        return rds;    }

 

private ByteBuffer loadData(int offset, int length) throws IOException {        // return fc.map(MapMode.READ_ONLY, offset, length).load();        ByteBuffer b = ByteBuffer.allocateDirect(length);        fc.position(offset);        fc.read(b);        b.rewind();        return b;    }

 

Considering the actual application of our system, the dbf file will be refreshed every few seconds. The size after the refresh is basically the same, and the format is the same, the size of each row is the same.

 

Pay attention to the highlighted part of the code above, and the ByteBuffer and byte arrays will be created repeatedly. In our application scenarios, we can use a cache mechanism to reuse them to avoid repeated creation. You must know that there are more than 5000 lines of a quote file. To avoid so many new and GC files, it is certainly good for performance.

 

I added a CacheManager class to complete this job:

Import java. nio. byteBuffer; import java. util. arrayList; import java. util. list; public class CacheManager {private ByteBuffer byteBuffer = null; private int bufSize = 0; private List <byte []> byteArrayList = null; private int bytesSize = 0; public CacheManager () {} public ByteBuffer getByteBuffer (int size) {if (this. bufSize <size) {byteBuffer = ByteBuffer. allocateDirect (size + 1024*8); // multiple allocations to avoid the next re-allocation Newly assigned this. bufSize = size + 1024*8;} byteBuffer. clear (); return byteBuffer;} public List <byte []> getByteArrayList (int rowNum, int byteLength) // rowNum indicates the number of rows, that is, the number of bytes [] required, byteLength is the size of the byte array {if (this. bytesSize! = ByteLength) {byteArrayList = new ArrayList <byte []> (); this. bytesSize = byteLength;} if (byteArrayList. size () <rowNum) {int shouldAddRowCount = rowNum-byteArrayList. size () + 100; // allocate 100 rows for (int I = 0; I <shouldAddRowCount; I ++) {byteArrayList. add (new byte [bytesSize]) ;}return byteArrayList ;}}

 

CacheManager manages a ByteBuffer that can be used repeatedly and a list of byte [] that can be used repeatedly.

 

The getByteBuffer method is used to return a cached ByteBuffer. It re-creates ByteBuffer only when the cached ByteBuffer is smaller than the specified size. (To avoid this situation as much as possible, we always need a larger ByteBuffer ratio ).

 

The getByteArrayList method is used to return the cached byte [] list. Only when the number of required bytes [] is smaller than the required number, more bytes [] will be created. If the cached bytes [] are of different lengths, re-create all byte [] (this is not possible, because the size of each line will not change, the code is just in case ).

 

Transform loadRecordsWithOutDel to recordsWithOutDel_efficiently and adopt the cache mechanism:

public List<byte[]> recordsWithOutDel_efficiently(CacheManager cacheManager) throws IOException {        ByteBuffer bb = cacheManager.getByteBuffer(getCount() * getRecordLength());        fc.position(getDataIndex());        fc.read(bb);        bb.rewind();        List<byte[]> rds = new ArrayList<byte[]>(getCount());        List<byte[]> byteArrayList = cacheManager.getByteArrayList(getCount(), getRecordLength());        for (int i = 0; i < getCount(); i++) {            byte[] b = byteArrayList.get(i);            bb.get(b);            if ((char) b[0] != '*') {                rds.add(b);            }        }        bb.clear();        return rds;    }

 

In the new recordsWithOutDel_efficiently, we allocate the cached ByteBuffer and cached byte [] From CacheManager. Instead of allocating from the system, this reduces repeated memory allocation and GC. (In addition, recordsWithOutDel_efficiently returns the byte [] list instead of the Record list)

 

My test showed that the optimization Step 4 was to use the cache method, which reduced the time from about 5 ms to more than 2 ms, which was roughly doubled.

 

At this point, we only read the file to the memory. Next, create a quote object for each row and read each column of data from byte. I found that it took much more time to read files than 70 ms to convert over 5000 rows of data without optimization. This is the optimization strategy we need to introduce next.

 

To be continued...

 

 

Binhua Liu Original article, reprint please indicate the original address http://www.cnblogs.com/Binhua-Liu/p/5615299.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.