Unmapping MappedByteBuffer

Zhong Yu zhong.j.yu at gmail.com
Sat Nov 3 08:28:54 PDT 2012


On Sat, Nov 3, 2012 at 4:21 AM, Mark Thornton <mthornton at optrak.com> wrote:
> On 03/11/12 02:59, Zhong Yu wrote:
>>
>> (cc Doug: a non-trivial use case for
>> ReentrantLock.isHeldByCurrentThread())
>>
>> On Fri, Nov 2, 2012 at 5:24 AM, Alan Bateman <Alan.Bateman at oracle.com>
>> wrote:
>>>
>>> On 02/11/2012 01:29, Jeff Hain wrote:
>>>
>>> :
>>>
>>>    That's modulo the fact that MappedByteBuffers can't be
>>> explicitly and portably unmapped (Bug ID: 4724038), so
>>> you can't always use them.
>>>
>>> Yes, a very difficult issue that many people have looked at but didn't
>>> come
>>> up a solution that addresses all the concerns, see:
>>>
>>> http://bugs.sun.com/view_bug.do?bug_id=4724038
>>
>> (I just saw it questioned on SO:
>> http://stackoverflow.com/questions/13204656 )
>>
>> I think we can solve the problem by enforcing that any thread
>> accessing the buffer must "own" it first, and there can only be one
>> owner:
>>
>>          bb.own();
>>
>>          bb.get(0);
>>          ....
>>          bb.get(n);
>>
>>          bb.disown();
>>
> That wouldn't be compatible with existing use of MappedByteBuffer. However
> you could perhaps apply that strategy to a new class (possibly a subclass of
> MappedByteBuffer). You could do without the disown() method --- legal usage
> would still be legal, only faulty use might get an exception in a different
> place.
>
> Mark
>

(change disown() to Closeable.close() method)

We can extend the idea to allow concurrent owner threads; each owner
will have to explicitly call close(). Probably something like

    try( CloseableByteBuffer cbb = mbb.newThreadLocalView() )
    {
        // access cbb
    }

public class CloseableByteBuffer implements Closeable
{
    Thread ownerThread = Thread.currentThread();

    void assertOwning()
    {
        if(ownerThread==null)
            throw new IllegalStateException("closed");
        if(ownerThread!=Thread.currentThread())
            throw new IllegalAccessError("not owner");
    }

    @Override
    public void close()
    {
        assertOwning();

        ownerThread = null;

        /* ref counting business */
    }

    public byte get(int index)
    {
        assertOwning();

        return bb.get(index);
    }

    ...
}


More information about the nio-dev mailing list