In my recent interview by explaining a situation they asked if the process is thread-safe
There are two synchronized methods one is static and other is not static i.e., non-static Method A and static Method B. These two methods access a shared data.
Now thread A calls non-static method A and thread B is calls static method B. Is this thread safe and explain y?
No, it's not thread-safe. For it to be thread-safe the different threads have to access the shared data using the same lock, but the two methods use different locks. Putting synchronized on a static method uses the class as a lock, putting synchronized on an instance method uses the object as a lock.
If the threads use different locks then neither thread is blocked, and both can access or modify the data concurrently. Even if the threads are only accessing data, and neither modifies it, locking would assure memory visibility. Without the shared lock you can't rely on that visibility. Unrestricted concurrent access would be safe only if the data is immutable and is already safely published.
Assuming the shared data has to be mutable, the fix would be for both methods to use the same lock. You can always specify your own lock if you use a synchronized block (rather than adding synchronized to the method), so the instance method could use:
public void yourInstanceMethod() {
synchronized(WhateverYourClassIs.class) {
// code accessing shared data
}
}
Related
Here my question is: I have a class with 2 methods one is non static synchronized and another is non static non synchronized method. Now 2 threads trying to access same instance of synchronized and non synchronized methods at a time. What will happen if thread one access non static synchronized method first? Can it be possible second thread to access non static non synchronized method of same instance when first thread apply lock on same instance?
Thanks Chandra
Yes the second thread can access the non synchronised method. There is no lock needed to access the method and can be done so by any thread. If the methods were both in the below format.
1. Static and synchronized. Will have to wait on the class level lock
2. Non static and synchronized. Will have to wait on object level lock
something about static:
instances of class share static method
the similar questions:
Java: when to use static methods
What does the 'static' keyword do in a class?
I am confusing about:
static method just have only one memory block?
if i use static method in multithreading, will it block?
I am confusing about:
static method just have only one memory block? if i use static method
in multithreading, will it block?
The static keyword in Java simply means "without regard or knowledge of any particular instance of an object."
An instance method can use this to access the fields of its associated instance, but a static method has no associated instance and so this makes no sense.
In multithreading, thread safety involves protecting the consistency and integrity of mutable data. Because objects encapsulate the state of their instance fields, instance methods only need to be concerned about thread safety in those circumstances in which more than one thread will be accessing the same object.
So while thread confinement of an object is a valid thread safety policy for instances of a class, this same reasoning is invalid for static methods because they have no instance.
This has nothing to do with memory blocks at all. It just has to do with access. An object instance is accessed through a reference. If the reference is thread confined, then the object to which that reference points will always be thread safe. But any thread anywhere that can access your class can potentially get to its static members because no reference to an instance is needed to use them.
Static methods are non-blocking by default. You can implement your own synchronization/thread safety policy and have your static method block if you wish.
Each thread has its own stack space, each time a thread calls a method (static or virtual) that call allocates a stack frame, which holds local variables. nothing about this is specific to static methods.
Static methods can be called concurrently by multiple threads, unless you specifically do something to thwart that, such as requiring that the caller acquire a lock (such as using the synchronized keyword).
Static methods are good for cases where there is no shared state. They may be ok in cases accessing or modifying threadsafe shared state, depending on what level of concurrency is needed and how efficient the threadsafe things being accessed are.
Look out for bottlenecks. Putting the synchronized keyword on a static method may be a problem as that limits your application to calling it with only one thread at a time. Alternative strategies including using atomic objects, using threadsafe data structures designed for high concurrency, or using thread confinement may be preferable to locking.
static method just have only one memory block?
No, methods don't have memory blocks. Threads executing those methods do. Each thread will have it's own memory on the stack where it stores all the method arguments and variables.
if i use static method in multithreading, will it block
A thread cannot access the memory of another thread, but if there is some resource that belongs to all instances and is supposed to be accessed sequentially, then you can synchronize or lock the static method, thus making it a blocking one. Otherwise, no.
Even though there is one instance of a static method, each thread gets its own stack-frame, which means each thread can exercise the same method but in a separate "world" from other threads.
Threads always get their own stack, even for a singleton class (one instance):
so, when to use static methods and when to not?
The main reason for not using static methods everywhere is that they are difficult to unit-test barring manipulating compiled code (Powermock), so static methods should have no dependencies that would require mocking, i.e. the test calls the real method with an input and asserts the output, verbatim, in two steps.
Non-static methods allow you to isolate your test solely to that method by stubbing, mocking, or spying on objects that the method depends on.
I know that
synchronized(objA) {
objA.readSomething();
}
protect object from being modified by another thread. But what if objA is declared as
class A {
public B objB;
public void readSoemthing() {
objB.readSomething();
}
}
and during the following block, another thead calls objB.modifySomething()? Suppose that thread somehow has its own reference to objB.
Will that be safe? if not, what's the proper way of handling it (i.e. I don't want any thread to modify anything inside A, even if it's a field that points to a different object, I don't want that object being modified).
synchronized(objA) {
objA.readSomething(); // at this point antoher thread calls objB.modifySomething()
}
The first part of your question is incorrect. The synchronized block only makes sure that no other thread can enter a block of code that is also synchronized on the object referenced by objA while the synchronized block is executing.
So any other thread might modify objA concurrently, unless all the methods that modify objA are synchronized.
Now that you know that, you also know that any other thread can get objB from objA and do whatever it wants with objB, unless all the methods of objB are also synchronized on objA.
This is why encapsulation is critical in thread-safe classes. All the methods accessing (read or write) shared state of an object should go through a synchronized method of that object. And the shared state should never be exposed to the outside.
That would not be thread safe. That's why you should "encapsulate" objB inside of objA by disallowing direct access to it (i.e. make it private).
I know that
synchronized(objA) {
objA.readSomething();
}
protect object from being modified by another thread. But what if objA
is declared as
This doesn't prevent objA from being modified by another thread, it ensures that another thread cannot obtain the monitor of objA while calling objA.readSomething() from the piece of code you posted.
You are not really protecting against modification with synchronized. All you are doing is preventing two threads from accessing that same method concurrently (or any other method or code block that uses the same object instance for synchronization). Synchronization is about concurrency (i.e. multi-threading) not write protection.
If you absolutely don't want modifications you should use the modifiers private or protected so that the respective write method is only accessed from the class(es) you want.
If on the other hand you want to avoid concurrent modifications, or avoid reading while writing (and vice-versa) you need to synchronize the read and write methods with the same object (in your case ObjA). It might also make sense to use the right modifiers to protect the methods from being accessed from classes you don't want.
Also remember that if a Thread has gained access to the synchronisation monitor of an object it can call all the methods that are synchronising on the same object.
I am new to java thread application please tell me How to write program, every thread access same list of object in multithreading application?
is there any good link to read?
You can make sure your List (or any Collection) will be thread safe by using the relevant methods in the Collections class.
From the API:
public static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list.
For example
static List mySharedList = Collections.synchronizedList(new ArrayList());
Try to access your list with same instance or make it static and make it Synchronized to make your list thread-safe.
You can use a static list so that there would be only one copy at any time. Also make sure to use syncronised methods for thread-safe.
To access the same instance of your list from all threads, make it static. Eg:
private static List myList;
Then make the accessing method thread-safe (i.e. Make it so that only one thread can access it at one time, so as to avoid conflicts). Eg:
public static synchronized updateList(String parameters) {
// Do something
}
Yes, all threads are able to access the same instance of any objects (incl. classes). Because a memory space is created on per-application (i.e. per-process) basis. Then a process contains all threads inside, incl. implicit 'main' one, with shared memory space.
If an object is used in one thread only, there are no any concurrency issues. You need no any 'synchronization', locking etc. But sometimes you may have to share something between thread. If both reading and writing can be done in a few threads simultaneously, it means you need synchronize by this object to deal with so called 'racing'.
You don't have to make a field as static for a shared object to make it thread-safe. If necessary, you can just pass this object as a parameter into a class which extends Thread class (or it may be even a local variable in enclosing class method in case of anonymous class, etc.)
So all you need is just synchronize by this object. You can synchronize either explicitly inside a method:
synchronized (obj) {
// doing a thread-safe stuff
}
or you can make a method synchronized entirely for an obj's class using such method modifier. In this case it will be synchronized implicitly and automatically on invocation of the method like "synchronized (this) {..}" block:
public void synchronized methodFoo() {
}
As for reading, I read 'Java in a Nutshell', chapter 5.7. "Threads and Concurrency". It was very helpful for me because of overview of all multi-threading possibilities in Java.
Among online resources, official Sun/Oracle's tutorial may be helpful for the beginners: http://docs.oracle.com/javase/tutorial/essential/concurrency/ (which has been already mentioned in another answers).
I have created 2 objects and 2 threads.
Assume m1() and m2() are synchronized methods.
t1.m1();
t2.m2();
can both threads can execute simultaneously ? is it possible both synchronized methods can execute simultaneously?
Synchronization happens on specific instances. Synchronized methods synchronize on the instances the method is called on. Thus, t1.m1() and t2.m2() can execute simultaneously if and only if t1 and t2 refer to different instances.
Yes, if both are non-static and are executed using two different instances.
Explanation added.
Because monitor is actually associated with the instance. So, if one thread acquired the lock on one instance, the thread is free to invoke the method on the other instance.
They can execute simultaneously, since synchronized methods lock on the instance.
synchronized void someMethod(){
}
is the same as
void someMethod(){
synchronized(this){
}
}
So every instance has its own lock to synchronise on.
Static methods use the class instance instead (SomeClass.class).
Yes, if they are instance methods of different instances, they are synchronization does not happen.
Synchronization is always done on a monitor. Only one thread can access a monitor at a time.
When you are synchronizating methods, the monitor is either the object (non-static) or the Class-object (static methods).
You should think of
public synchronized void myMethod(){
...
}
as:
public void myMethod(){
synchronized (this) {
...
}
}
Since you are having two independent object instances with a synchronized method, you have 2 different monitors.
Result: Both Threads can work simultaneously.