Debian Codegraph @

test/jpypetest/test_synchronized.py

raw symbols SCIP
1 # *****************************************************************************
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 # See NOTICE file for details.
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 # Cause a fail
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 # Increment the global resource
51 glob += 1
52
53 # Wait for a while
54 time.sleep(0.1)
55
56 # If anything else accessed then it was a fail
57 if glob != 1:
58 success = False
59
60 # Decrement the global resoure
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 # Create 10 threads trying to access the same resource
78 for i in range(0, 10):
79 tl.append(MyThread())
80
81 # Release them at the same time
82 for i in tl:
83 i.start()
84
85 # Wait for all to finish
86 for i in tl:
87 i.join()
88
89 # Verify they did not trample each other
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