I have a java class that has some (private static) synchronized methods which I want to call from native code as well. with some example code it becomes more clear what I mean
public class SomeClass {
private static synchronized void method() {
//do something that needs synchronization
}
}
and the associated native code (C++)
void someFunction(JNIEnv * env) {
jclass someClass = env->findClass("SomeClass");
jmethodID methodId = env->GetStaticMethodID(jclass, "method", "()V");
env->MonitorEnter(jclass); // <--- IS THIS NEEDED/ALLOWED
env->CallStaticVoidMethod(jclass, methodId);
env->MonitorExit(jclass); // <--- IS THIS NEEDED/ALLOWED
}
So what I am wondering is if I need to call MonitorEnter/MonitorExit, or if the method synchronization is enforced already by the synchronized attribute on SomeClass.method().
I am not so much interested in rewriting the code. I can think of a few solutions to work around this, but I am interested in what the behaviour is, given a synchronized method that is called from native code.
Section 8.4.3.6 synchronized Methods of the Java Language Specification says that declaring the method synchronized has the same effect as adding a synchronized block within the method.
No, explicit MonitorEnter / MonitorExit are not needed. According to The JNI guide,
...it is preferable to express synchronization constructs in the Java programming language. If, for example, a static native method needs to enter the monitor associated with its defining class, you should define a static synchronized native method as opposed to performing JNI-level monitor synchronization in native code.
Even though your case of calling a Java method from the native code (and not vice versa) isn't directly discussed in the spec, the opposite is not stated either, so I would assume that it works similarly.
If you own SomeClass you can just do
public class SomeClass {
private static synchronized void method() {
//do something that needs synchronization
}
private static void synchronizedMethod() {
method();
}
}
and just call synchronizedMethod() from C++.
Related
I have a class ClassA that has a public void doSomething() method. This ClassA is widely used in different applications; some require synchronized and others do not. It is also the case that I do not want the (tiny, but non-zero) performance hit associated with calling a synchronized method when I do not need this.
Suppose that ClassB will call doSomething() and requires that this is synchronized, yet ClassC does not require this. What are the ways that I can achieve this in the design of my program?
Is it sufficient to have the method in ClassB:
private synchronized void doSomething() {
this.classAInstance.doSomething();
}
thus avoiding the need to specify ClassC's doSomething() as synchronized?
When you have a need to use the same class with and without synchronization, a common approach is to make an interface, and provide two implementations - a non-synchronized class with the actual implementation, and a thin wrapper that adds synchronization.
Here is a simple example: suppose you are building a class with two operations - getSomething and setSomething. The interface may look like this:
interface Demo {
void setSomething(Something value);
Something getSomething();
}
Now the non-synchronized implementation may look like this:
class DemoImpl implements Demo {
private Something theSomething;
public void setSomething(Something value) {
theSomething = value;
}
public Something getSomething() {
return theSomething;
}
}
Finally, the synchronized implementation:
class SyncDemoImpl implements Demo {
private DemoImpl impl = new DemoImpl();
public synchronized void setSomething(Something value) {
impl.setSomething(value);
}
public synchronized Something getSomething() {
return impl.getSomething();
}
}
Bear in mind that this is purely an academical exercise. I don't see any practical reason why a resource should need a selective synchronized access. Either you need it, or you don't. If you have to do this, you are setting yourself up for long hours of troubleshooting few months down the line. If I could, I would rethink the design.
So,
You say - 'some require synchronized and others do not'
I take that means you know exactly each and every part of your code that needs Synchronized access, and can differentiate it from those that need to save this overhead. If so: You have two options:
Get rid of the synchronized modifier of the method all together and get all the callers that need synchronization to synchronize before the call is made. Thus:
synchronized (classAInstance){
classAInstance.doSomething(); // the doSomething() is non-synchronised
}
Those parts in code that call this method and do not need synchronized access can call the method directly.
Make two methods, one that is synchronized and other that is not synchronized. Change the callers to call based on the way you want the access to be controlled.
I am reading static method synchronization in java. Where i read static methods get a lock on object of java.lang.class. I was trying to understand the concept of java.lang.class and its role in static method synchronization and i have these questions.
I was reading the blog where it says every class in Java has an instance of java.lang.Class and all instances of a class share this object. Instance of java.lang.Class describes type of object? What is the role of java.lang.Class here? How does it describes type of object?
Secondly for static method synchronization, we need to get the monitor of java.lang.Class. Why is that? Why do we need a lock on java.lang.Class monitor? Why not on the instance of our own class for example Test(my own custom class)?
Can someone elaborate on it. I am really sorry because it sounds a pretty basic question but i am pretty new to this concept.
Tentative explanation, although admittedly it is not fully correct. For whatever class C, when you do:
final C c = new C();
two Objects are involved here: the Class<C> object (which is provided via the context classloader) and the c instance. c will know which class it is via its .getClass() method (defined in Object).
The fact that the new keyword is able to establish a "backlink" to the correct Class is the responsibility of the JVM implementation. While this is certainly mentioned in the JLS, I cannot tell where...
Now, more to the point.
If you have a method declared as:
synchronized void whatever() { someCode(); }
then it is roughly equivalent to (why roughly: see below):
void whatever()
{
synchronized(this) {
someCode();
}
}
That is, this code is synchronized at the instance level.
If the method is static however, this:
public static synchronized void meh() { someOtherCode(); }
is roughly equivalent to (why roughly: see below):
public static void meh()
{
synchronized(getClass()) {
someOtherCode();
}
}
One thing to note is that all Class objects are singletons; no matter how many instances of class C you create, .getClass() will always return the same Class object. Try this:
public static void main(final String... args)
{
final String s1 = "foo";
final String s2 = "bar";
System.out.println(s1.getClass() == s2.getClass()); // true
}
Add the fact that getClass() is equivalent to this.getClass() and you get the picture. Class itself being an Object, it obeys the monitor rules of any Object.
And since here we always refer to the exact same object, monitor rules apply ;)
Now, "roughly": in the code written above, the logic is the same; however, depending on how you write that code, the bytecode may differ; but the JIT will have its say in it and will eventually optimize code paths.
Every object in java is an instance of some class. In addition to that every class is an object too, so it is an instance of some class too.
Instance of java.lang.Class describes type of object?
Not exactly. java.lang.Class is a class of class instance.
What is the role of java.lang.Class here? How does it describes type of object?
It describes type of all types.
Secondly for static method synchronization, we need to get the monitor of java.lang.Class. Why is that? Why do we need its instances lock not our class lock?
You need to synchronize on some object. Static methods have no access to this, by definition, so the only shared thing that is left is a class where they are defined.
Secondly for static method synchronization, we need to get the monitor
of java.lang.Class. Why is that? Why do we need a lock on
java.lang.Class monitor? Why not on the instance of our own class for
example Test(my own custom class)?
There are two ways to synchronize static methods. One is this :
static synchronized void methodName(){}
In this case, user need not care about acquiring the lock externally. Internally all the static methods of this class which are marked as synchronized will need to acquire the lock to its java.lang.class instance. It is very obvious in this case that, instance(new Class()) locks cannot be acquired over here as the method is static, and static methods can exist without instances of the class. Also static methods are shared by all the objects of that class. So instances of this class is out of question.
Other way is to use synchronized block inside static method :
static void methodName() {
synchronized(ClassName.class){ // same as above approach
// method defination
}
synchronized(this){ } // not allowed. compile time error
// to get lock of instance of this class you do as shown below. But it is not useful at all. Because every time u acquire different instance. So synchronization is not achieved.
synchronized(new Class()){ }
}
OR
static OtherClass lock = new OtherClass();
static void methodName() {
synchronized(lock){ // instance of other class can be used a well
// method defination
}
}
The class java.lang.Class is a representation of your class. The primary use of the class Class is to use reflection (gettings constructors and methods for example).
For this think of it as a meta object... all instances of one class share this meta object.
The designers of java have chosen that monitors have to work on objects. To have a monitor on a static method you have to use the afore mentioned meta object (or class).
I think that this made the design and implementation of the monitor for synchronized blocks easier. Also, as mentioned, the class java.lang.Class is used for reflection and therefore is there already.
I was wondering if there is a situation where this statement will be true and needed. All the examples I have seen only synchronize on the "this" reference. Can someone tell me how a block of code in one object can be synchronized on any other reference apart from this ?
Yes the statement is true.
There are several reasons why one would want NOT to use an intrinsic monitor (synchronized(this)) - one of these reasons is that it can create liveness issues - in the code below, B uses an instance of A as a lock, maybe to control access to that variable. If another thread uses that same instance of A and tries to run a.methodA(), it will be blocked until methodB() is over.
So using an intrinsic monitor exposes the synchronization policy and can lead to subtle bugs and performance issues.
public class A {
public synchronized void methodA() {}
}
public class B {
A a = new A();
public void methodB() {
synchronized(a) {
// do something a little long
}
}
public A getA() {return a;}
}
If A had used an internal monitor that problem would not be possible.
public class A {
private final Object lock = new Object();
public void methodA() {
synchronized(lock) {}
}
}
Another scenario where using ad hoc monitors makes sense is when a class contains 2 (or more) unrelated objects, that both need to be accessed in a synchronized manner. Using 2 monitors instead of one reduces contention as the 2 objects can now be accessed concurrently.
public class SyncTest{
private Object obj = new Object();
public void func1() {
synchronized(obj) {
obj.something();
}
}
Yes it can be done.
The synchronize block will use that object as a lock, rather than the whole class. People that use synchronized(this) { } put an exclusive lock on the whole object, which might be what you want. However, you might have something like a persister, which is the only thing that needs to be synchronized. synchronized(persister) { }, would provide a less granular way of doing this.
In Java, you can use synchronized constructs to create instrinsic locks on any object reference, yes. Read the relevant Java Tutorial.
The immediate example of not using synchronized with this is when synchronizing on the Class object, which is how static synchronized methods work. In reality, there are plenty of valid uses. You may want to avoid using synchronized (this) in favor of an internal implementation lock as otherwise you are setting a restriction that you use the lock internally, which other code you're not aware of might violate.
You should know, however, that often times you can replace synchronized usage with a ReentrantLock. You can read more about this in my post here.
Suppose I have a Utility class,
public class Utility {
private Utility() {} //Don't worry, just doing this as guarantee.
public static int stringToInt(String s) {
return Integer.parseInt(s);
}
};
Now, suppose, in a multithreaded application, a thread calls, Utility.stringToInt() method and while the operation enters the method call, another thread calls the same method passing a different s.
What happens in this case? Does Java lock a static method?
There is no issue here. Each thread will use its own stack so there is no point of collision among different s. And Integer.parseInt() is thread safe as it only uses local variables.
Java does not lock a static method, unless you add the keyword synchronized.
Note that when you lock a static method, you grab the Mutex of the Class object the method is implemented under, so synchronizing on a static method will prevent other threads from entering any of the other "synchronized" static methods.
Now, in your example, you don't need to synchronize in this particular case. That is because parameters are passed by copy; so, multiple calls to the static method will result in multiple copies of the parameters, each in their own stack frame. Likewise, simultaneous calls to Integer.parseInt(s) will each create their own stack frame, with copies of s's value passed into the separate stack frames.
Now if Integer.parseInt(...) was implemented in a very bad way (it used static non-final members during a parseInt's execution; then there would be a large cause for concern. Fortunately, the implementers of the Java libraries are better programmers than that.
In the example you gave, there is no shared data between threads AND there is no data which is modified. (You would have to have both for there to be a threading issue)
You can write
public enum Utility {
; // no instances
public synchronized static int stringToInt(String s) {
// does something which needs to be synchronised.
}
}
this is effectively the same as
public enum Utility {
; // no instances
public static int stringToInt(String s) {
synchronized(Utility.class) {
// does something which needs to be synchronised.
}
}
}
however, it won't mark the method as synchronized for you and you don't need synchronisation unless you are accessing shared data which can be modified.
It should not unless specified explicitly. Further in this case, there wont be any thread safety issue since "s" is immutable and also local to the method.
You dont need synchronization here as the variable s is local.
You need to worry only if multiple threads share resources, for e.g. if s was static field, then you have to think about multi-threading.
While discussing a Java synchronization question, someone made a comment that the following snippets are not equivalent (and may compile to different bytecodes):
public synchronized void someMethod() {
//stuff
}
and
public void someMethod() {
synchronized (this) {
//stuff
}
}
Are they equivalent?
They are equivalent in function, though the compilers I tested (Java 1.6.0_07 and Eclipse 3.4) generate different bytecode. The first generates:
// access flags 33
public synchronized someMethod()V
RETURN
The second generates:
// access flags 1
public someMethod()V
ALOAD 0
DUP
MONITORENTER
MONITOREXIT
RETURN
(Thanks to ASM for the bytecode printing).
So the difference between them persists to the bytecode level, and it's up to the JVM to make their behavior the same. However, they do have the same functional effect - see the example in the Java Language Specification.
It should be noted, that if the method is overridden in a subclass, that it is not necessarily synchronized - so there is no difference in that respect either.
I also ran a test to block a thread trying access the monitor in each case to compare what their stack traces would look like in a thread dump, and they both contained the method in question, so there is no difference there either.
I made the original comment that the statements are identical.
In both cases, the first thing that happens is that the calling thread will try to acquire the current object's (meaning, this') monitor.
I don't know about different bytecode, I'll be happy to hear the difference. But in practice, they are 100% identical.
EDIT: i'm going to clarify this as some people here got it wrong. Consider:
public class A {
public synchronized void doStuff()
{
// do stuff
}
}
public class B extends A {
public void doStuff()
{
// do stuff
// THIS IS OVERRIDE!
}
}
In this case doStuff() in class B still overrides doStuff() in class A even though it is not synchronized.
Synchronized keyword is never part of the contract! Not for subclasses, not for interfaces, not for abstract classes.
I made the original comment. My comment was that they are logically equivalent, but compile to different bytecode.
I didn't add anything else to justify it at the time because there's not much to justify really-- they just do compile to different bytecode. If you declare a method as synchronized, then that synchronization is part of the method's definition. A synchronized block within a method isn't part of the method's definition, but instead involves separate bytecodes to acquire and release the monitor, as one of the posters above has illustrated. Strictly speaking, they're slightly different things, though to the overall logic of your program, they're equivalent.
When does this matter? Well, on most modern desktop VMs, hardly ever. But for example:
a VM could in principle make optimisations in one case but not the other
there are some JIT compiler optimisations where the number of bytecodes in the method is taken as a criterion for what optimisations to make
a VM without a JIT compiler (admittedly few nowadays, but maybe on an older mobile device?) will have more bytecodes to process on each call
Yes. Using the synchronized keyword on an instance method uses 'this' as a monitor ,also using it on a class method (static method) uses the class' Class object (Foo.class).
This way you can synchronize entire methods, and in the same time, synchronize it with a code snippet in another method using the synchronized-block style.
I can't see any functional difference - both synchronize their entire method bodies on (this). How did the person who commented that these are different justify their statement?
They are not quite equivalent in function. Other code could use reflection to see if your method has the synchronized modifier, but there is no way to tell if a method contains a synchronized block without reading its bytecode.
The ability to determine if a method is synchronized occasionally comes in handy. Personally, I've used that flag to avoid redundant locking when doing synchronization in aspect-oriented programming.
MyObject myObjectA;
MyObject myObjectB;
public void someMethod() {
synchronized (this) {
//stuff
}
}
public void someMethodA() {
synchronized (myObjectA) {
//stuff
}
}
public void someMethodB() {
synchronized (myObjectB) {
//stuff
}
}
In this case:
someMethod blocks entire class
someMethodA blocks myObjectA only
someMethodB blocks myObjectB only
someMethodA and someMethodB can be invoked at the same time