| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
import sys |
| 19 |
import threading |
| 20 |
import time |
| 21 |
import jpype |
| 22 |
from jpype import synchronized |
| 23 |
import common |
| 24 |
|
| 25 |
fail = False |
| 26 |
if fail: |
| 27 |
|
| 28 |
class _JMonitor(object): |
| 29 |
def __init__(self, obj): |
| 30 |
pass |
| 31 |
|
| 32 |
def __enter__(self): |
| 33 |
pass |
| 34 |
|
| 35 |
def __exit__(self, exception_type, exception_value, traceback): |
| 36 |
pass |
| 37 |
|
| 38 |
def synchronized(obj): |
| 39 |
return _JMonitor(obj) |
| 40 |
|
| 41 |
success = True |
| 42 |
glob = 0 |
| 43 |
obj = None |
| 44 |
|
| 45 |
|
| 46 |
class MyThread(threading.Thread): |
| 47 |
def run(self): |
| 48 |
global glob, success, obj |
| 49 |
with synchronized(obj): |
| 50 |
|
| 51 |
glob += 1 |
| 52 |
|
| 53 |
|
| 54 |
time.sleep(0.1) |
| 55 |
|
| 56 |
|
| 57 |
if glob != 1: |
| 58 |
success = False |
| 59 |
|
| 60 |
|
| 61 |
glob -= 1 |
| 62 |
|
| 63 |
|
| 64 |
class SynchronizedTestCase(common.JPypeTestCase): |
| 65 |
|
| 66 |
def setUp(self): |
| 67 |
common.JPypeTestCase.setUp(self) |
| 68 |
global glob, success, obj |
| 69 |
obj = jpype.JClass("java.lang.Object")() |
| 70 |
|
| 71 |
def testSynchronized(self): |
| 72 |
global glob, success |
| 73 |
glob = 0 |
| 74 |
success = True |
| 75 |
|
| 76 |
tl = [] |
| 77 |
|
| 78 |
for i in range(0, 10): |
| 79 |
tl.append(MyThread()) |
| 80 |
|
| 81 |
|
| 82 |
for i in tl: |
| 83 |
i.start() |
| 84 |
|
| 85 |
|
| 86 |
for i in tl: |
| 87 |
i.join() |
| 88 |
|
| 89 |
|
| 90 |
self.assertTrue(success) |
| 91 |
|
| 92 |
def testSyncronizedFail(self): |
| 93 |
with self.assertRaisesRegex(TypeError, "Java object is required"): |
| 94 |
with jpype.synchronized(object()): |
| 95 |
pass |
| 96 |
with self.assertRaisesRegex(TypeError, "Java primitives cannot be used"): |
| 97 |
with jpype.synchronized(jpype.JInt(1)): |
| 98 |
pass |