jpype icon indicating copy to clipboard operation
jpype copied to clipboard

share java object through multiprocessing error in windows

Open 617976080 opened this issue 8 years ago • 11 comments

from multiprocessing import Process, Queue, freeze_support
import time, jpype
ext_classpath = './Calculator.jar'
jvmArg = '-Djava.class.path=' + ext_classpath
class APP:
    def __init__(self, q):
        self.q = q
        pass
    def trigger(self, funs):
        for fun in funs:
            self.q.put(fun)
            time.sleep(5)
            pass
    def notify(self, *args):
        print(*args)
class Calculator:
    def __init__(self, q, calculator):
        self.q = q
        self.calculator = calculator
    def isPrim(self,n):
        print('isPrim({0}):{1}'.format(n, self.calculator.isPrim(str(n))))
        time.sleep(1)
def write(q):
    funs = [('isPrim', 10), ('isPrim', 11)]
    APP(q).trigger(funs)
def read(q : Queue, object):
    calculator = Calculator(q, object)
    while True:
        try:
            e = q.get(True)
            getattr(calculator, e[0])(*e[1:])
        except:
            pass
        time.sleep(0.01)
if __name__=='__main__':
    freeze_support()
    jpype.startJVM(jpype.getDefaultJVMPath(), jvmArg)
    javaCalculator = jpype.JPackage('API').Main(10000000, 100)
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,javaCalculator))
    pw.start()
    pr.start()
    pw.join()
    pr.terminate()

I want to build a application name "primer calculator".I want to build and run GUI in python, and handle the computed work in java. So I write this demo to test. First, it create two process pw and pr. pw simulated the GUI process to send the computed work request, and the pr simulated the compution process to call the java object to notify the request. The demo operated great in MacOS.this is the example:

('isPrim', 10)
isPrim(10):False
('isPrim', 11)
isPrim(11):True

But it hava some error in the windows.This is the error massage:

Traceback (most recent call last): File "ProcessJavaDemo.py", line 58, in pr.start() File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \process.py", line 105, in start self._popen = self._Popen(self) File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \context.py", line 322, in _Popen return Popen(process_obj) File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \popen_spawn_win32.py", line 65, in init reduction.dump(process_obj, to_child) File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) _pickle.PicklingError: Can't pickle <class 'jpype._jclass.API.Main'>: attribute lookup API.Main on jpype._jclass failed Traceback (most recent call last): File "", line 1, in File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \spawn.py", line 105, in spawn_main exitcode = _main(fd) File "C:\Users\xushaojun\AppData\Local\conda\conda\envs\py\lib\multiprocessing \spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) EOFError: Ran out of input

It think it is result of the different implements between MacOs and Windows, but multiprocessing only can share Value, Array and some other base type variate. I have no way. This is my first time submit the issue, and my english is not good. I hope somebody can give me some suggestions. Think you.

617976080 avatar Oct 22 '18 13:10 617976080

Can you edit your message to use three back ticks to denote the start and end of code blocks? I suggest using the preview to see if the formatting is correct. I am having difficulty understanding the issue has it is currently formatted.

Thrameos avatar Oct 24 '18 00:10 Thrameos

Can you edit your message to use three back ticks to denote the start and end of code blocks? I suggest using the preview to see if the formatting is correct. I am having difficulty understanding the issue has it is currently formatted.

Think you very much. I have edited my issue.

617976080 avatar Oct 24 '18 11:10 617976080

Yes it is definitely an implementation difference between mac and pc. The pc version is pickling the arguments to create a fork in the processed. As jpype objects are not able to be pickled the call fails. The only solution would be to create the Java object on the other end of the fork. Thus rather than passing the created calculator, you instead pass the arguments to call main. Of course this only works if the passed arguments are also simple types.

Thrameos avatar Oct 24 '18 12:10 Thrameos

I would suggest that what you are trying to accomplish would work much better using threads. One python thread calls java methods directly and the other serves the gui. You can even use a dispatch on the python side to launch java methods that return results later. We properly support java threading including Futures and Execute pools. When combined with Proxies it would achieve your goal.

Thrameos avatar Oct 24 '18 12:10 Thrameos

I would suggest that what you are trying to accomplish would work much better using threads. One python thread calls java methods directly and the other serves the gui. You can even use a dispatch on the python side to launch java methods that return results later. We properly support java threading including Futures and Execute pools. When combined with Proxies it would achieve your goal.

Think you very much. I also have considered use the threads instead of process. However, as you know, it will take much time to get the result of whether a integer is a prime or not. So, I hope to use multiprocessing to accelerate the work. Jpype is really a wonderful project.And If the Jpype can support the multiprocessing.It will be better.

617976080 avatar Oct 24 '18 12:10 617976080

I would suggest that what you are trying to accomplish would work much better using threads. One python thread calls java methods directly and the other serves the gui. You can even use a dispatch on the python side to launch java methods that return results later. We properly support java threading including Futures and Execute pools. When combined with Proxies it would achieve your goal.

It is only be allow to create the java object in main process? If can create the java object in calculate process, the problem would be solve.I try it, but it throw errors.

617976080 avatar Oct 24 '18 13:10 617976080

Each process can allocate its own jvm thus you can have as many copies as you want . The difficulty is not with jpype so much as the method by which items are being passed from one process to another. Python does this by serializing python objects in one process, transmitting the serialized stream and then deserializing the object in the other context. As our objects contain references to the JVM it is not possible to push the data in that fashion.

You have two options. The first is to send the objects yourself by calling java serialization. Simply convert the object into a stream of bytes that can be sent to another process and then unpack them on the other side.

 public byte[] pack(Serializable object) throws IOException
  {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream())
    {
   
        try (ObjectOutputStream out = new ObjectOutputStream(bos))
        {
          out.writeObject(object);
          out.flush();
        }
        return bos.toByteArray();
      }
    
    catch (IOException ex)
    {
      throw new RuntimeException(ex);
    }
  }

  public Serializable unpack(byte[] buffer) throws IOException
  {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(buffer))
    {
      {
        try (ObjectInputStream in = new ObjectInputStream(bis))
        {
          return (Serializable) in.readObject();
        }
      }
   
    catch (IOException | ClassNotFoundException ex)
    {
      throw new RuntimeException(ex);
    }
  }

I am currently working the ability to call serialization into jpype so that objects can automatically be pickled in mixed python/java data structures, but that is currently a low priority. The problem being that the serialized objects unpack into a new jvm and can carry with them all referenced objects. Also I had some difficulty getting pickle to call the wrapper creation as pickle assumes that the imported modules in both the packing and unpacking are the same. Dynamic classes like jpype would require an automatic dispatch requiring every java class to exist as a descendant of a single module. This can be accomplished through the same method as JPackage, but I have never gotten to the point of a working prototype.

The second is to use a threading system. You can use multiple cores on the same machine to perform work by in as many threads as you allocate. This won't allow you to run on many machines, but it will allow parallelism.

If you are really trying to use large scale parallelism, I would recommend allocated dedicated java processes using an interprocess communication method such as thrift. You just spawn the jobs on the multiple machines and then use thrift to call the methods on the remote processes. Though it is outside the scope of jpype, that is the method that I use when doing large scale jobs.

Thrameos avatar Oct 24 '18 16:10 Thrameos

Each process can allocate its own jvm thus you can have as many copies as you want . The difficulty is not with jpype so much as the method by which items are being passed from one process to another. Python does this by serializing python objects in one process, transmitting the serialized stream and then deserializing the object in the other context. As our objects contain references to the JVM it is not possible to push the data in that fashion.

You have two options. The first is to send the objects yourself by calling java serialization. Simply convert the object into a stream of bytes that can be sent to another process and then unpack them on the other side.

 public byte[] pack(Serializable object) throws IOException
  {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream())
    {
   
        try (ObjectOutputStream out = new ObjectOutputStream(bos))
        {
          out.writeObject(object);
          out.flush();
        }
        return bos.toByteArray();
      }
    
    catch (IOException ex)
    {
      throw new RuntimeException(ex);
    }
  }

  public Serializable unpack(byte[] buffer) throws IOException
  {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(buffer))
    {
      {
        try (ObjectInputStream in = new ObjectInputStream(bis))
        {
          return (Serializable) in.readObject();
        }
      }
   
    catch (IOException | ClassNotFoundException ex)
    {
      throw new RuntimeException(ex);
    }
  }

I am currently working the ability to call serialization into jpype so that objects can automatically be pickled in mixed python/java data structures, but that is currently a low priority. The problem being that the serialized objects unpack into a new jvm and can carry with them all referenced objects. Also I had some difficulty getting pickle to call the wrapper creation as pickle assumes that the imported modules in both the packing and unpacking are the same. Dynamic classes like jpype would require an automatic dispatch requiring every java class to exist as a descendant of a single module. This can be accomplished through the same method as JPackage, but I have never gotten to the point of a working prototype.

The second is to use a threading system. You can use multiple cores on the same machine to perform work by in as many threads as you allocate. This won't allow you to run on many machines, but it will allow parallelism.

If you are really trying to use large scale parallelism, I would recommend allocated dedicated java processes using an interprocess communication method such as thrift. You just spawn the jobs on the multiple machines and then use thrift to call the methods on the remote processes. Though it is outside the scope of jpype, that is the method that I use when doing large scale jobs.

Think you very much!

617976080 avatar Oct 25 '18 14:10 617976080

Pickle support was added and documentation of the proper use of multiprocessing has been added.

Thrameos avatar Feb 29 '20 06:02 Thrameos

Hi, I'm new to the multiprocessing with Python. I have a java function to use in Python, I used jpype to wrap the function. I need to use the function with multiprocessing and I used the following code block to run the function.

data_split = np.array_split(data, num_of_processes)
ctx = mp.get_context("spawn")
pool = ctx.Pool(num_of_processes)
data = pd.concat(pool.map(func, data_split))
pool.close()
pool.join()

But the code gives an error Can't pickle <java class 'java.lang.String'>: attribute lookup java.lang.String on jpype._jstring failed

I read the documentation of jpype but I could not understand the following sentence.

This can be overcome by wrapping Queue to first encode to a byte stream using the JPickle package

How I can implement this wrapping of Pool? What is the referenced library?

atayuksel avatar Apr 24 '20 13:04 atayuksel

Queues call pickle which can't be extended to Java classes, thus rather than directly creating a Queue you have to create a derived class that calls the Java pickler to create a bytes object then pass the byte object to a normal queue get() and then recover it on the put().

Looking at the multiprocessing code it does not appear they gave much in the way of customization. It just creates a SimpleQueue which can't be changed. But there may be an easy patch. All queue use a specific pickler...

_ForkingPickler = context.reduction.ForkingPickler

It you monkey patch the multiprocessing.queues module you should be able to convince it to use a different pickler. I would have to read further to give you a better answer.

I recommend setting up a simple test first where you create your own multiprocess with a simple queue, get that working on Java objects, then try to apply the monkey patch. So long as each multiprocess patches in the JPickler it should all work.

Thrameos avatar Apr 24 '20 14:04 Thrameos