java: running thread methods in the same class - java

I have three threads on the same class i.e
Thread A obj, Thread B obj, Thread C obj and that class contains 3 static synchronized methods so when we start the 3 threadssaya.meth1, b.meth2, c.meth3what will happen – does all three will execute or only one ?`
Update:
interviewr asked me this question so actually i do have any code to write it here

The methods are static and synchronized.. So, the lock will be on the class object.. Not on the instances of the class.. So the methods will run one after another.... Thread2 and Thread3 will have to wait until thread1 completes method1().. syncronization is NOT at method level.. it is always at object level... beit instance object or class object.

then they will execute it one by one in serial manner as the methods are static synchronized. So the lock will be held at Class Level not the method level. Hence one thread will acquire lock and others will have to wait.
You should try running this and see.

Once you invoke a synchronized method, the VM will automatically ask a grant of access for the object on which you are invoking the method. If that is given it will enter the synchronized method. Upon exit til will release this access right. While holding the rights, no-one else is allowed into any synchronized method on the same object, effectively serializing the requests.
does that make sense?
Synchronization is designed to make things thread-safe and avoid race conditions, and this fashion reduce access to at most one thread. There is no way for the program to find out whether two synchronized methods A and B are otherwise connected, so it has the policy of least tolerance.
If you have more synchronization that necessary, e.g. that A and B needs to be mutually exclusive and C and D needs to be mutually exclusive, but not between, say A and C then the advice is typically to modularise your code so A+B goes into one object while C+D goes into another, hence avoiding to step over each others toes

If execution for objects of the same class attempt to enter the same synchronized method (whether static or not)from different threads, they will be synchronized (i.e. execute one at a time).

The primary difference between static synchronized methods and non static synchronized methodsis that non-static synchronized methods hold a lock on the instance of the class whereas static synchronized methods lock on the class object.
Since in java there exists one class object per class, only one thread can execute inside a static synchronized method in the same class.
For non-static synchronized methods only one thread can execute inside a static synchronized method in the same object
And one more point is that synchronization is at object level not as method level.

Related

Do static methods block?

Let's say I have a class defined as:
public class MyClass {
private static int data;
public static staticMethod(int val){
... do something with data based on val ...
}
}
And now let's say I have many Java threads running in my application that make calls to the static method
MyClass.staticMethod(int)
Will the method block upon each invocation? i.e., if thread 1 calls the method first and while that run of the method is being executed, thread 2 calls the static method, will the second thread have to wait until the first execution is completed?
If the answer is no, then when would it make sense to use static data members in a un-"synchronized" way?
No, that is not part of the static keyword. If you want to synchronize two threads accessing the same method, use other possibilities, such as synchronized (method or statement), or stuff from the java.util.concurrent package.
Will the method block upon each invocation?
No. A plain static method doesn't block other threads. (But a static synchronized method can block other threads ... or be blocked by other threads.)
If the answer is no, then when would it make sense to use static data members in a un-"synchronized" way?
It is OK if the data member if the member is volatile ... modulo the limits of volatile.
It is OK if the data member is a final reference to an thread-safe type.
It is OK if the data member is thread confined. (This is unlikely since the member is visible to all threads by virtue of being static. But it is possible.)
It is OK if something else is taking care of synchronization, or if you are using Lock objects for mutual exclusion, etcetera ... though you probably would say that these "don't count".
As you have written it, no. Multiple threads will not block until another thread has finished the method execution. This is true regardless of whether the method is static.
To enforce that only a single thread has access to the method, you must make the method synchronized.
public static synchronized staticMethod(){
No, not unless the class/method is declare Synchronized.
http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

Can a class with getters separate from input processing methods be considered "thread-safe"?

I was reading though a book on Java and there was this exercise question where they declared a class with one private variable, one public void method that did some expensive operation to calculate and then set the private variable, and a second public method to return the private variable. The question was "how can you make this thread-safe" and one possible answer was "synchronize each of the two methods" and one other possible answer was "this class can not be made thread-safe".
I figured the class could not be made thread-safe since even if you synchronize both methods, you could have a situation that Thread1 would invoke the setter and before Thread1 could invoke the getter, Thread2 might execute and invoke the setter, so that when Thread1 went and retrieved the result it would get the wrong info. Is this the right way to look at things? The book suggested the correct answer was that the class could be made thread safe by synchronizing the two methods and now I'm confused...
I figured the class could not be made thread-safe since even if you synchronize both methods, you could have a situation that Thread1 would invoke the setter and before Thread1 could invoke the getter, Thread2 might execute and invoke the setter, so that when Thread1 went and retrieved the result it would get the wrong info. Is this the right way to look at things?
You are correct with this. There is no way to guarantee that a thread will not have called either of the methods in between your calls of each of the methods, from within the class.
If you do want to do this, that will require a wrapper class.
So if the class with the getter and setter is like so:
class Foo
{
private static int bar;
public static synchronized void SetBar(int z) { ... }
public static synchronized int GetBar() { ... }
}
The wrapper class would look something like this:
class FooWrapper
{
public synchronized int SetGetBar(int z)
{
Foo.SetBar(z);
return Foo.GetBar();
}
}
The only way to guarantee this will work is if you can guarantee that all calls will go through your wrapper class rather than directly to class Foo.
When you make those two synchronized, the getter and setter themselves are thread-safe. More specifically:
When you call the setter, you are guaranteed that the value of the variable is what you set it to when the method finishes.
When you call the getter, you are guaranteed that the return value is the value of the variable when you made the call.
However, making the getter and setter themselves thread-safe does not mean that the application as a whole (i.e. whatever is using this class) is thread-safe. If your thread wants to call a setter then get the same value upon invoking the getter, that involves synchronization on a different level.
As far as thread-safety is concerned, a thread-safe class need not control how its methods are invoked (for example, it need not control which way the threads interleave their calls), but it needs to ensure that when they are, the methods do what they are supposed to.
synchronized in Java is an object-wide lock. Only one synchronized method of any given object can be executed on any given thread at a time. Let's have this class:
class Foo
{
private int bar;
public synchronized void SetBar() { ... }
public synchronized int GetBar() { ... }
}
Thread 1 calls SetBar(). Thread 1 acquires the object lock.
Thread 2 wants to call SetBar(), but Thread 1 holds the lock. Thread 2 is now queued to acquire the lock when Thread 1 will release it.
Thread 1 finishes executing SetBar() and releases the lock.
Thread 2 immediately acquires the lock and starts executing SetBar().
Thread 1 calls GetBar(). Thread 1 is now queued to acquire the lock when Thread 2 will release it.
Thread 2 finishes executing SetBar() and releases the lock.
Thread 1 acquires the lock, executes GetBar(), and is done with it.
You did the work twice, but you didn't cause any race condition. It may or may not be erroneous to do the work twice, depending on what it is.
A frequent pattern is to have one thread produce content and one other thread do something useful with it. This is called the producer-consumer pattern. In this case, there is no confusion over who or what tries to SetBar() and what tries to GetBar().

Can one thread access a synchronized non-static method and another thread access a synchronized static method at the same time?

I got this asked in an interview a few days ago. Can one thread access a synchronized non-static method and another thread access a synchronized static method at the same time? The methods belong to the same class. I know the answer is yes but I want to know how it is possible. Thanks.
The synchronization object for a non-static method is the object itself (this).
The synchronization object for a static method is the .class instance.
Both are different. Hence you can.
The important thing to consider, is what object are those methods being synchronized on? For a non-static (just a regular, object method) it will be synchronized on the actual instance of the class (this - the object you create using 'new'). For a static method, you are synchronizing it on the class itself (there is no instance object).
These are two different objects, so the synchronization will not stop the methods running at the same time.
Because syncrhonization is not enforced on the same two objects:
first synchronized lock (for non-static method) is acquired over the object instance,
second synchronized lock (for static method) is acquired over the class instance.
If you have a synchronized non-static method on a class, the lock object will be YourClass.this. If you have a static synchronized method on the same class, the lock object will be the YourClass.class. These are two different locks that does not mutually exclude each other. So that is the reason why the two threads can access the two methods in the same time.
ObPedantry: Not if this is java.lang.Class.class (and the lock hasn't been released by calling a java.lang.Object.wait).

Java Threads and synchronization

I have a web app that uses some jars written by me.
My challenge is that i have a critical (but fast) section in my code.
1 - I have an object of a given class that has a couple of static fields. Let's call this class A
2 _ A exposes a not static method that access the static fields. for reading and writting. Lets call this method doJob.
3 - Every request instantiates an object of the class A and calls doJob.
A a = new A(); a.doJob();
4 - I assume that every request is creating a new Thread where doJob is executed.
5 - If I define doJob as public synchronized void doJob () {//Do the job} only one Thread at a time will be executing the method and the others will keep waiting.
The question is: Is it all right what i am saying?
You are right, but doJob will be synchronized at instance level, so doJob method could be executed in the same time by two or more different threads on two or more instances of class A. If you want doJob to be executed only by one thread at a time (e.g because it chages static fields) you should either declare it static or synchronize the whole method body using a static field as locking object.
Given that you're trying to guard static (i.e. one per class) fields with non-static (i.e. one per object) monitors, I would say that the "only one thread at a time will be executing the method and the others will keep waiting" claim does not hold.
No.
Marking an instance method as synchronized means the same that doing
public void myMethod() {
synchronized(this) {
...
}
}
So, you can only guarantee that two threads are not running the same method of the same object. The same method from another object can be run simultaneously.
Try to synchronize with a more "static" object. I would use the class object itself, or some static (and inmutable) member.
yes, you're outline is correct. and it does technically bottleneck the system while the other threads wait for access. and this is perfectly fine and normal as long as you avoid putting any heavy processing or i/o within the synchronized block.

What is the difference between synchronized(this) and synchronized(ClassName.class)?

I read somewhere that synchronized(this) should be avoided for various reasons. Yet some respectable code that I encountered uses the following in the constructor:
public SomeClass(Context context) {
if (double_checked_lock == null) {
synchronized (SomeClass.class) {
if (double_checked_lock == null) {
// some code here
}
}
}
}
Is there really a difference between synchronized(this) and synchronized(SomeClass.class)?
synchronized(this) is synchronized on the current object, so only one thread can access each instance, but different threads can access different instances. E.g. you can have one instance per thread.
This is typically useful to prevent multiple threads from updating an object at the same time, which could create inconsistent state.
synchronized(SomeClass.class) is synchronized on the class of the current object ( or another class if one wished) so only one thread at a time can access any instances of that class.
This might be used to protect data that is shared across all instances of a class (an instance cache, or a counter of the total number of instances, perhaps) from getting into an inconsistent state .
this is different for each instance.
ClassName.class is not.
Therefore, synchronized(this) will allow multiple instance to run simultaneously.
The synchronized keyword, when applied to a class locks on the class, and when it's applied to this locks on the current object instance. From the Java Language Specification, section 8.4.3.6, 'synchronized Methods':
A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
Each java Object can have a lock. This lock can be held by at most one thread at a time, any other thread has to wait to get the lock of the same object.
synchronized(this) acquires the lock of the instance this for the current thread. The method can run parallel on different instances (different values for this and therefore different locks)
synchronized(SomeClass.class) acquires the lock of the global class object of SomeClass. Only one instance of the method can run as all object instances lock on the same global object (same lock).
These are 2 different object to lock on:
'this' refer to current instance context, so creating multiple instances will have no effect if, for example, each thread using a different instance and lock on it. 'this' can be referred only on non-static context.
the 'class' is a static member of the Java Class and there is exactly one instance of it. You can lock on it in both static and non-static context.
synchronized(this) synchronizes on the instance of the object.
synchronized(SomeClass.class)uses the instance of the Class object that represents SomeClass, which is global for all instances in the same classloader.
Thus, these are different constructs with different semantics.
Using synchronized alone, or as a method modifier, also synchronizes on the instance's semaphore, which is normally used to prevent contention between multiple threads accessing that instance as a shared resource (i.e. a List).
The thread you refer states that it's a better practice to use a private instance, as synchronizing directly on your object instance may be dangerous. For that you'd use:
class MySharedResourceClass {
private SomeClass lock = new SomeClass();
public doSomething() {
synchronized (lock) {
// Do something here
}
}
}

Categories

Resources