Ксакеп, Вот с помощью Unsafe (сорри за самописный стек, думаю, реализация заинтересует)
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.misc.Unsafe;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Qbold
*/
public class AOS {
public static long[] st;
public static long next_;
public static String str_;
public static Unsafe unsafe;
public static void main(String[] args) {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
st = new long[]{-1, -1, -1, -1};
push("ABCD", 1);
push("ABCDA", 1);
push("abgf", 0);
push("4555fgff", 2);
push("4555fgf11111111f", 2);
push("4MMMMMM", 2);
System.out.println(pop(1));
push("ABCDB", 1);
System.out.println(pop(1));
System.out.println(pop(1));
System.out.println(pop(1));
System.out.println(pop(0));
System.out.println(pop(2));
System.out.println(pop(2));
System.out.println(pop(2));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ex) {
Logger.getLogger(AOS.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void push(String s, int pos) {
try {
byte[] b = s.getBytes("UTF-8");
ByteBuffer buf = ByteBuffer.allocateDirect(b.length + 10);
buf.position(0);
buf.putShort((short) b.length);
buf.put(b);
buf.putLong(st[pos]);
st[pos] = getAddress(buf);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(AOS.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static String pop(int pos) {
long obj = st[pos];
if (obj + 1 == 0) {
return "null";
}
ByteBuffer obj2 = getObjectFromAddress(obj);
obj2.position(0);
getData(obj2);
obj2.flip();
st[pos] = next_;
obj2.flip();
return str_;
}
public static void getData(ByteBuffer bf) {
try {
byte[] d = new byte[bf.getShort()];
for (int i = 0; i < d.length; i++) {
d[i] = bf.get();
}
str_ = new String(d, "UTF-8");
next_ = bf.getLong();
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(AOS.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ByteBuffer getObjectFromAddress(long ad) {
if (ad + 1 == 0) {
return null;
}
short size = unsafe.getShort(ad);
byte[] data = new byte[size + 10];
for (int i = 0; i < data.length; i++) {
data[i] = unsafe.getByte(ad + i);
}
return ((ByteBuffer) ByteBuffer.allocate(data.length).position(0)).put(data);
}
public static long getAddress(ByteBuffer o) {
try {
Field f = Buffer.class.getDeclaredField("address");
f.setAccessible(true);
return f.getLong(o);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(AOS.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
}