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.
Related
I am new to Java I just want to know what if whole class in Java will be synchronized, what will be the possible problems? I know the concept of class level locking, which is different.
Marking the whole class synchronized would be misleading. Although there are situations when it makes perfect sense to make all methods of a class synchronized, a class typically contains other declarations that cannot be synchronized.
For example, class constructor cannot be marked synchronized. Same goes for fields of a class. One could mistakingly assume that fields in a class marked synchronized would be accessed in a synchronized way, but that is not something that Java does automatically. Of course language designers could declare that synchronized on class level applies only to methods, but such decision would be somewhat arbitrary.
The synchronized keyword can only be used on method declarations and as synchronized blocks. When used on a method declaration, it's the same as adding a synchronized block around the contents of the method, synchronizing on this. There is nothing preventing you from synchronizing every method of a class. If you use synchronized keyword on every method declaration that would mean that only one method of the class can execute concurrently. In a multi-threaded application this could cause poor performance, but there isn't anything to prevent you doing it.
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
}
}
So I have a Singleton class and in it a non-static public method that is called by multiple threads. In the non-static method I have local references to objects created by a Stored Procedure which I surmise means the 'new' keyword gets called somewhere.
1 public void someMethod(SomeObjectParameter parameter) {
2
3 Thing thingOne = synchornizedStoredProcedureCall():
4 doSomethingWith(thingOne);
5 doSomethingElseWith(thingOne);
6
7 }
Currently lines 3 through 5 are in a synchronized code block which I would like to reduce down to just having the stored procedure call as synchronized.
So... Say we have two threads, Thread1 and Thread2. Thread1 is about to execute line 3 and Thread2 is about to execute line 4. Since this is a local reference, will each thread maintain a different reference or will synchornizedStoredProcedureCall overwrite the reference to thingOne as doSomethingWith is about to use it?
What if thingOne is declared final or if I made it immutable?
will each thread maintain a different reference or will synchornizedStoredProcedureCall overwrite the reference to thingOne as doSomethingWith is about to use it?
The different threads have different stacks. The thingOne is stored in the per-thread stack so cannot be overwritten by the other thread. You also need to make sure that the synchornizedStoredProcedureCall() is returning a different instance of Thing each time and not a static or instance variable. Both threads need to be working on different Thing instances.
As long as the doSomethingWith(...) and doSomethingElseWith(...) calls are thread safe and only work with thingOne argument and constants (etc), protecting just the synchornizedStoredProcedureCall() should be fine.
As #Marko points out, without seeing the Thing class, we cannot be guaranteed that it is thread-safe and not storing internal state.
The answer depends on a lot of details that you haven't presented. Many details about the Thing class matter: it could have some internally shared state that may not be thread-safe (see the Flyweight design pattern). These facts must be documented in the class Javadoc; otherwise it would be very difficult to find it out from source code.
Thingone is thread safe anyway as it is declared threadlocal on the stack. If thingone was an instance variable not declared within a method, you would have problems; but it isn;t - so you don't.
your thingOne is local variable. it is thread safe. Each thread gets its own copy of locals.
You need to be sure that thingOne is not shared. Even though it is returned from a synchronized method, if it is a member of the singleton returned from synchornizedStoredProcedureCall , your implementation is no longer thread safe.
Each thread will maintain a different reference. That would be even the case if someMethod was static.
You still have to be sure that the Thing instances are thread safe themslef. E.g. the Thing class doesn't have static fields nor the two Thing instance have a non-static field pointing to the same object, or if they do they handle them in a thread safe way.
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).
Is the following code threadsafe ?
public static Entity getInstance(){
//the constructor below is a default one.
return new Entity();
}
Assuming the constructor itself is thread-safe, that's fine.
It would be very unusual for a constructor not to be thread-safe, but possible... even if it's calling the default auto-generated constructor for Entity, the base constructor may not be thread-safe. I'm not saying it's likely, just possible :)
Basically there's no magic thread-safety applied to static methods or instance methods or constructors. They can all be called on multiple threads concurrently unless synchronization is applied. If they don't fetch or change any shared data, they will generally be safe - if they do access shared data, you need to be more careful. (If the shared data is immutable or only read, that's generally okay - but if one of the threads will be mutating it, you need to be really careful.)
Only static initializers (initialization expressions for static variables and static { ... } blocks directly within a class) have special treatment - the VM makes sure they're executed once and only once, blocking other threads which are waiting for the type to be initialized.
It depends on the details of the Entity constructor. If the Entity constructor modifies shared data, then it is not.
It's probably thread safe, but what's the point? If you're just using a factory method to redirect to the default constructor then why not use the constructor in the first place? So the question is: what are you trying to achieve? The name getInstance() suggests a singleton (at least that's common practice), but you clearly don't have a singleton there. If you do want a singleton, use a static inner holder class like this:
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
private static final class InstanceHolder {
public static final Singleton INSTANCE = new Singleton();
}
}
but if you don't, why bother with such a factory method, as you're not adding any value (method name semantics, object pooling, synchronization etc) through it
Thread safety is about access to shared data between different threads. The code in your example doesn't access shared data by itself, but whether it's thread-safe depends on whether the constructor accesses data that could be shared between different threads.
There are a lot of subtle and hard issues to deal with with regard to concurrent programming. If you want to learn about thread safety and concurrent programming in Java, then I highly recommend the book Java Concurrency in Practice by Brian Goetz.
Multiple threads could call this method and each one will get an unique instance of 'Entity'. So this method 'per se' is thread safe. But if there is code in the constructor or in one of the super constructors that is not thread safe you might have a safety problem anyhow.