In Brian Goetz's article about safe construction techniques you could read:
[...] often when an object owns a thread, either that thread is an inner class or we pass the this reference to its constructor (or the class itself extends the Thread class). If an object is going to own a thread, it is best if the object provides a start() method, just like Thread does, and starts the thread from the start() method instead of from the constructor. While this does expose some implementation details (such as the possible existence of an owned thread) of the class via the interface, which is often not desirable, in this case the risks of starting the thread from the constructor outweigh the benefit of implementation hiding.
I guess that with the following code there shouldn't be any problem. Since it is not an inner class nor I am passing a reference of this. But I want to be sure.
private Controller controller;
private View view;
public Facade() {
view = new View();
controller = new Controller(view);
controller.start();
}
I keep getting NetBeans warnings though... So is this code safe or unsafe?
The main reason do not start thread in constructor - do not expose "this" before "this" is created (after constructor executed). In your code I do not see such code like:
new Thread(this);
So it should be fine.
Related
Say I have class A which is not thread safe, and I want to launch a bunch of threads with class B, is passing a new instance of class A to each thread of class B a good design choice, since if I passed one instance of class A to all of them there would be concurrency issues?
#NotThreadSafe
class A {
...
}
class B extends Thread {
private A a;
B(A a) {
this.a = a;
}
}
class C {
public static void main(String [] args) {
for(int i = 0; i < 10; i++) {
A a = new A();
B b = new B(a);
b.start();
}
}
}
It pretty much depends on the characteristics of class A.
In general, passing creating an instance of A per thread will solve (not solve, but rather eliminate) concurrency issues.
Assuming class A has some internal state (otherwise class A itself is supposed to be thread safe), each thread B will read/update different fields in memory that belong to its "own" object of class A, so no concurrency issue here, unless...
A is very "heavy" object and creating it will have a big performance / memory impact.
Using design of object per thread won't meet the functional requirements of the product. For example, you have to share something between threads (somthing = some common state) because if one thread B, say, has done some work and has updated that internal state, another thread B should be able to benefit from (be able to read) that state otherwise it will do that work again or do it in a wrong.
Let's assume that you have overridden run in the B class. Your example doesn't make sense otherwise. (The start() call would invoke Thread::run which returns immediately. Ooops!)
Some terminology first.
A thread confined object is an object is an object whose state is accessible to one and only one thread.
If an object is thread confined, then it doesn't matter if the class is thread-safe or not.
(Depending on how broadly you define "state" of course. Lets assume that the object's state is the closure of the object that the object's methods may access. Or something like that.)
So what we have in your example is a non-thread-safe object a that is created in main and then used solely in a single child thread.
Prior to the start() call, each a is thread confined to the main thread. For this part of the program, thread-safety (of A) doesn't matter.
Once control reaches the child thread's run() method, each a is thread confined to the child thread. From then on, thread safety doesn't matter.
Now what about the start() call itself?
The Java Memory Model (JLS 17.4) specifies that there is a happens-before relationship between the call to start() in the main thread, and the call to run() in the child thread. This happens-before ensures that writes to the A or B instances or anything else made by the main thread prior to the start() call are guaranteed to be visible to the child thread on / after entering the run method body. This is a strong guarantee. Any compliant Java 5.0 or later implementation will behave this way, on any platform.
However, changes made to the A, etc in the main thread after the start() call are not guaranteed to be visible to the child. They may or may not be. If that happens, your code is likely to be broken. But the example code doesn't show it happening.
In summary, this approach is thread-safe. Whether it is "viable" depends on whether your design meets the requirements. For example, the B threads need to share state, this approach doesn't address that.
Finally, extending Thread is generally thought to be a bad idea. A better idea would be to instantiate plain Thread instances, passing them a Runnable as a constructor parameter. Alternatively, use an ExecutorService and let that take care of thread management.
There is a big difference between using a single instance and a new instance each time. (Eg if the class represents a Person then, it's the difference between the same person or a different one every time. This makes the program outcome different between circumstances and this question therefore doesn't make sense.)
If we assume the class holds no data and therefore the program outcome will not change whether or not a single instance or multiple are used, then
a good design choice, since if I passed one instance of class A to all
of them there would be concurrency issues
it would be a terrible design choice and not solve any concurrency issues, as the external data each class instance works on will still be the same and the threads will fight over the data.
To fix concurrency issues you must use synchronization.
I have class "RequestContext" which has scope request. This class has atribute listOfItem.
now I have class MyMapper where I need to use this list. Now when I want to listOfItems I always call context.getListOfItem() but problem is that I have a lot of private method where I need to repeat this a lot of times. It is ok when I define this atribute in constructor ? It is thread safe ?:
public abstract class MyMapper{
#Autowired
protected RequestContext context;
private final List<String> listOfItem;
public MyMapper() {
this.listOfItem = context.getListOfItem(); // is this thread safe and ok ?
}
public Object map(Object entity){
}
}
Yes, that is thread safe as long as it is declared as a prototype scope bean, and you need to create an init() method that is called by Spring:
#PostConstruct
public void init() {
listOfItem = context.getListOfItem();
}
The RequestContext is only accessible from single thread (the one allocated to handle the request), the constructor is not re-entrant by nature of the creation of the object just before it's call.
Be careful not to confuse this with the listOfItem somehow being safe from reentrancy problems though, just because it is locked down in the MyMapper object does not stop it from being shared by a getter, if one were available (there isn't in your case). I also see that it's an abstract class, but because the listOfItem is private, subclasses will not have access to it. Any leaked reference of that List could be manipulated by concurrent threads were there to be any copies made of the reference (since Lists are mutable in Java).
As this safety is your intent, create a unit test that checks the visibility of the field and fails if accessing the field via reflection does not throw the appropriate exception. You may also want to comment the field with your own internal marker annotation to indicate the field is thread safe. This helps with documentation, and as an annotation, potential future automation (such as a test base that could look for all such annotations and automatically run the reflection test).
It looks very clean! Keep up the good work.
Basically i was going trough a multithreading guide in developers.android.com when i saw something that confused me...(i am reffering to this article
http://developer.android.com/training/multiple-threads/create-threadpool.html
)
In the Define the Thread Pool Class section where they mention that the class should have a private constructor in order to make it singleton, the writer claims that by doing this the code would not require synhronization. I am confused why this is thread safe, as altough it is a singleton it can still be referenced by multiple threads simultaneously causing memory consistency errors etc.
What they mean is:
Since the constructor is private only a method inside the class itself may create an instance of that class
The only instance of that class created is through:
static
{
// Creates a single static instance of PhotoManager
sInstance = new PhotoManager();
}
The static { ... } block is thread safe because it is executed by the class loader, which is synchronized
I always wonder how just by implementing an interface , sub class acquires the behavior. For example if I implement Runnable interface my subclass start behaving as thread, but what if I implement all the methods defined in interface Runnable but not write "implementing Runnable", subclass doesn't behave as Thread. Same with EventListeners . Please help me understanding this behavior.
By implementing an interface I, you're declaring that the Object "is a" I and that it'll contain all the methods defined by this interface. If you just implement the methods of the interface I, but don't declare it by an implement statement, compiler won't be able to determine that your class "is a" I and you won't be able to use it as a I-type.
No, Runnable has nothing to do with behaving like a thread. It just contains a plain, simple, void nullary method called "run".
Not specifying implements Runnable will just make your object not an instance of the Runnable type, which means you won't be able to pass it to a method requiring a Runnable. This is just an issue of type safety. The method you call could also accept an Object and invoke run using reflection, with the exact same behavior.
When you are implementing Runnable your class does not become thread and does not start behavior as thread. However if your class implements Runnable you can run it in context of thread:
class MyClass1 implements Runnable {
public void run() {
// this stuff will run in thread when thread's start() method is called
}
}
new Thread(new MyClass1()).start();
But java is strongly typed language. You can just create class like this:
class MyClass2 {
public void run() {
// this stuff will run in thread when thread's start() method is called
}
}
But it will not be Runnable. Therefore you cannot just send it to thread:
new Thread(new MyClass2()).start();
In this case you will get compilation error. Compiler cannot know that your class indeed implements method that looks like one that is declared in Runnable. You must declare this (as in first case).
A Runnable only allows your class to be run in a Thread. You still need e.g. a java.util.concurrent.Executor to actually run it in an actual Thread.
However, you can extend Thread which would allow you to call Thread.start().
To actually get out behavior from just implementing an interface, you would need a second object inspecting the classpath for classes implementing your interface using reflection, and then do something with that class.
Your question has two aspect:
Interface as a contract: Interfaces imposes a behavioral contract on a class implementing it. For example, If Car is an interface with some methods abstractly defining a car, any class implementing Car interface will have to define the methods of the car. You are free to actually implement the behavior.
Analogy of Runnable acting as thread is incorrect. What makes Runnable class act as thread is the the Thread class. Runnable just specifies the contract for a class to act as thread. Check this post.
This is not a subclassing behavior. In order to use subclass behavior you need to extend the class.
W.r.t interfaces these are just templates/contracts that are implemented by class. In order for runnable to work calling program need to instantiate a thread and when thread will start it will call run method implemented by your class.
I always wonder how just by implementing an interface , sub class acquires the behavior.
It doesn't 'acquire' any 'behaviour'. The subclass provides the behaviour. What implementing the interface does is provide the compile-time type signatures such that you can use the subclass where the interface is specified.
I am going through Hello Android (Android PDF/tutorial) and have now seen this syntax a couple of times. Can someone please explain to me what Java syntax is used when run Runnable is defined?
private class AndroidBridge {
public void callAndroid(final String arg) { // must be final
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "callAndroid(" + arg + ")" );
textView.setText(arg);
}
...
Is the code defining a Runnable object and overriding it's run method?
As Dave Newton indicated, this is an anonymous inner class implementing the Runnable interface.
As to why one would want to use this, it could be thought of as syntactic sugar of sorts. You'll notice that in your example, the code in run() has access to the same scope as where the anonymous inner class itself is defined.
This simplifies access to those members, as if you defined the class externally, you'd have to pass in a reference to any object whose members you wanted to invoke/use.
In fact, IIRC, this is actually what happens when Java compiles the anonymous inner class; if there are references to the outer containing class, the compiler will create a constructor that passes in a reference to the outer containing class.
The .post method expects a Runnable object, which in your code sample is declared anonymously and passed as the argument.
That will start a new thread for some long-running process.
The thread constructor needs a Runnable object, which has a run method that's called when the thread is ready.
When many Java apps start, all of the operations pile up on one thread, including the UI. I mainly use threads to avoid freezing up the UI if I'm doing something "heavy".
You've seen this happen when you click "execute" or something, and the UI suddenly is less than responsive. This is because the current thread doesn't have enough resources to build the UI and do whatever "execute" is asking.
So, sometimes that's done elsewhere, on a different thread, which needs a Runnable object.
It's worth noting that multithreading (where you make more than one thread on purpose) is notoriously difficult to work with, for debugging reasons mostly, IMO. But it is a useful tool, of course.
The code is defining an anonymous inner class that implements the Runnable interface, and implementing the run method to perform the appropriate actions.