3 messages in net.java.dev.jna.usersRe: [jna-users] Synchronizing access ...
FromSent OnAttachments
Albert StrasheimSep 19, 2007 5:04 pm 
Timothy WallSep 19, 2007 7:05 pm 
Albert StrasheimSep 20, 2007 2:55 am 
Actions with this message:
Paste this link in email or IM:
Paste this link in email or IM:
Atom feed for this thread
Paste this URL into your reader:
Subject:Re: [jna-users] Synchronizing access to a native libraryActions...
From:Timothy Wall (twal@dev.java.net)
Date:Sep 19, 2007 7:05:24 pm
List:net.java.dev.jna.users

Probably the easiest thing would be to simply wrap the JNA proxy with your own, which does the synchronization on every method call, e.g. something like this

public <T> synchronizedLibrary(<T> myInterface) { InvocationHandler handler = Proxy.getInvocationHandler(myInterface); return Proxy.newProxyInstance(classLoader, new Class[] { myInterface.getClass() }, new InvocationHandler() { public Object invoke(Object[] args) throws Throwable { synchronized(lock) { return handler.invoke(args); } } }); }

It might make sense to add something like this as a static method in Native, comparable to the Collections.synchronizedXXX() methods.

On Sep 19, 2007, at 8:05 PM, Albert Strasheim wrote:

Hello all

I'm wrapping a third party library that has some global structures that could potentially get corrupted if more than one thread calls into the native code at any given time.

However, due to the nature of my problem, I foresee that I might have more than one Java thread that might be calling into this library.

I think I want to synchronize access to the library. One option would be to write all my code as:

synchronized (MyLib.INSTANCE) { MyLib.INSTANCE.foo(); }

but this seems rather repetitive and error prone, so I'm hoping JNA could help out.

In general, it seems like it might be useful to have a mechanism to be able to register "functors" to be invoked just before and just after JNA calls the native library. One could configure this similarly to the type and function mappers.

If such a mechanism existed (or exists?), I could register a "lock" and a "unlock" functor to manage a Lock to synchronize access to the native library.

Any thoughts?

Regards,