multithreading - How can I safely and timely dispose a scarce shared resouce in Java? -


in parallel application, threads(32) in thread group use shared unmanaged , standalone disposable object.

we have same thing in our c/c++ app, , there use shared_ptr<> in order let object dispose , finalize after there no need object.

i tried apply same thing in java, , faced finalize() method. there problems, because of gc lazy sometimes, object doesn't identified unreachable object disposing/finalizing, called, there no warranty gc lets object invoke finalize() completely.

so came complex solution count down , track threads using object doesn't work too, know not reliable solution, , know faced unexpected results.

i'm wonder if there equivalent shared_ptr<> in java, or possible handle object via jni?

any ideas?

doing want needs effort, , never feel natural in java, because deterministic cleanup of resources is foreign java. has gotten bit better since java 7 though.

the best way work around this:

  1. add counter of type java.util.concurrent.atomicinteger java wrapper, initialised @ 1 (thanks @jules that, avoiding synchronized!).
  2. add addref method, throws if counter 0, returning this better use in try-statement.
  3. implement java.lang.autocloseable: close decreases count when not 0, , releases resource when count reaches 0.
  4. add finalizer final safety-net: log failure release resource earlier, , final release.
  5. add comment every variable / argument owns such reference , not try-with-resource, know call addref , close appropriate.

a try-with-resources-block using java wrapper:

try(resource.addref()) {     // thing } 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -