Created
November 3, 2012 02:56
-
-
Save bayou/4005639 to your computer and use it in GitHub Desktop.
SingleOwnerByteBuffer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer; | |
import java.util.concurrent.locks.ReentrantLock; | |
public class SingleOwnerByteBuffer | |
{ | |
final ReentrantLock lock = new ReentrantLock(); | |
ByteBuffer bb; | |
boolean disposed; | |
public SingleOwnerByteBuffer(ByteBuffer bb) | |
{ | |
this.bb = bb; | |
} | |
public int length() | |
{ | |
assertOwnedByCurrentThread(); | |
return bb.remaining(); | |
} | |
public byte get(int index) | |
{ | |
assertOwnedByCurrentThread(); | |
return bb.get(index); | |
} | |
public void dispose() | |
{ | |
lock.lock(); | |
try | |
{ | |
if(disposed) | |
return; | |
/* unmap or dealloc bb here */ | |
disposed = true; | |
} | |
finally | |
{ | |
lock.unlock(); | |
} | |
} | |
public void own() | |
{ | |
lock.lock(); | |
if(disposed) | |
{ | |
lock.unlock(); | |
throw new IllegalStateException("disposed"); | |
} | |
} | |
void assertOwnedByCurrentThread() | |
{ | |
if(!lock.isHeldByCurrentThread()) | |
throw new IllegalStateException("not owned by current thread"); | |
} | |
public void disown() | |
{ | |
lock.unlock(); | |
} | |
public static void main(String[] args) throws Exception | |
{ | |
//test1(100_000, 1000_000); | |
test2(100_000, 1000_000); | |
} | |
static public void test1(int cap, int repeat) throws Exception | |
{ | |
int sum=0; | |
long time = System.currentTimeMillis(); | |
ByteBuffer bb = ByteBuffer.allocateDirect(cap); | |
for(int r=0; r<repeat; r++) | |
{ | |
for(int i=0; i<cap; i++) | |
{ | |
sum += bb.get(i); | |
} | |
} | |
time = System.currentTimeMillis() - time; | |
System.out.printf("time=%,d, sum=%,d %n", time, sum); | |
} | |
static public void test2(int cap, int repeat) throws Exception | |
{ | |
int sum=0; | |
long time = System.currentTimeMillis(); | |
ByteBuffer bb0 = ByteBuffer.allocateDirect(cap); | |
SingleOwnerByteBuffer bb = new SingleOwnerByteBuffer(bb0); | |
bb.own(); | |
for(int r=0; r<repeat; r++) | |
{ | |
for(int i=0; i<cap; i++) | |
{ | |
sum += bb.get(i); | |
} | |
} | |
bb.disown(); | |
time = System.currentTimeMillis() - time; | |
System.out.printf("time=%,d, sum=%,d %n", time, sum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment