java - deallocating direct ByteBuffer when used in LibUSB -
libusb (usb4java) requires use of direct bytebuffers sending/receiving bulk transfers.
the problem according documentation java.nio.bytebuffer
direct bytebuffer out of java heap , therefore out of reach of garbagecollector.
i have implemented message sender/receiver in java use of libusb bulk sending, rapidly draining of ram.
private synchronized boolean send(string msg) { //... bytes = msg.getbytes("utf-8"); sendbuff = bytebuffer.allocatedirect(bytes.length); sendbuff.put(bytes); intbuffer = intbuffer.allocate(1); result = libusb.bulktransfer(handle, (byte) 0x02, sendbuf, intbuffer, 0); try { if (result < 0) throw new libusbexception(result); } catch (libusbexception e) { e.printstacktrace(); } return true; } // in separate thread public void run() { try { intbuffer transfered = intbuffer.allocate(1); int result; bytebuffer recbuffer = bytebuffer.allocatedirec(500000); while ((result = libusb.bulktransfer(handle, (byte) 0x81, recbuffer, transfered, 0)) >= 0) { final int transferlength = transfered.get(); final byte[] bytes = new byte[transferlength]; recbuffer.get(bytes); //.... } throw new libusbexception(result); } { logwriter.info("receiver thread finished."); client.connected = false; } }
i've figured out can reuse recbuffer
, use clear() reset before every call, sendbuff
variable length cannot reuse one.
if leave running more 20min of ram depleted. result in outofmemory exception, of time exit or thread lost.
any ideas on how property use bytebuffers in this?
Comments
Post a Comment