Anonymous class objects: which variables do they see? - java

A common situation when writing an Android app: scheduling a Runnable to make some drawing work on a View:
class MyView extends View {
...
private void start() {
final ScheduledExecutorService executor = Executors
.newScheduledThreadPool(1);
mMoverFuture = executor.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
if (isOutOfView()) {
mMoverFuture.cancel(false);
}
postInvalidate(); // Can I do this?
}
}, 0, REFRESH_RATE, TimeUnit.MILLISECONDS);
}
...
}
Particularly, I am not sure if I can call MyViews method postInvalidate() from the thread's run(). Which rules should one follow when judging which variables and methods are available to an anonymous class object?

According to Java rules an instance of InnerClass has direct access to the methods and fields of its enclosing instance. If you have doubts you can check it in Oracle documentation
Method postInvalidate, in its turn, is designed especially to be invoked outside of UI thread so it also doesn't violate Android View's restrictions.

There are no rules. You can call any variables from parent class. In your case all you need to remember it is thread safety. Take care about this, if it is important for you.

Related

Is it possible in multithreaded environment to use the singletons instance by only one thread?

I am using singleton classes, and I have more threads running. I want to achieve that while thread 1 is using a singleton instance, thread 2 is blocking, and after thread 1 finishes with the instance, the other thread can use it.
I use synchronized in getInstance(), but it only ensures that only one thread can request the instance at the same time. It does not ensure that only one thread can work with the instance at a time.
It is possible to make the code almost safe using a callback:
class MySingleton {
// no public getInstance() here
public interface Callback {
void doWithSingleton(MySingleton singleton);
}
public static synchronized void doWithSingleton (Callback cb) {
cb.doWithSingleton(instance);
}
}
Then use it:
MySingleton.doWithSingleton(new Callback() {
public void doWithSingleton(MySingleton singleton) {
singleton.method1();
singleton.method2();
}
});
This way, the singleton knows when the user will stop working with the instance, and can release the lock (exit the synchronized block / method). Same pattern may be used to implement anything that needs some init and cleanup that user must not forget to perform.
That the user will only work with the singleton within the given method is "ensured" by singleton instance only being available as a local variable in the callback. Note that this is not completely safe as you can't prevent user from copying the instance into a global variable - but it takes quite some effort for the user to break it.
Looks like a weird requirement. Still you could have something like Singleton provider that gives and takes back the singleton we are talking about.
This could be achieved even with static methods:
class SN {
private static final SN instance = new SN(....) // your thingy
private static final Lock instanceLock = ... // the lock protecting your thingy
public static SN get() {
lock.lock()
return instance
}
public static void giveBack(SN instance) {
if (null != instance) {
lock.unlock()
}
}
}
The invariant here is: as long I have reference to SN object, I am keeping access to SN.instanceLock.
Obviously you need to ensure that your user follows the typical get-finally-giveBack idiom.
But as others have suggested, best would be to avoid a need for such design and make the singleton thread safe.

When to use refactoring with "Convert Anonymous to Inner"?

Android Studio provides good refactoring items.
But when to do "convert anonymous to inner" is better?
For Example:
new Thread(new Runnable() {
#Override
public void run() {
// do something
}
})
After Refactoring:
new Thread(new MyRunnable());
private static class MyRunnable implements Runnable {
#Override
public void run() {
// do something
}
}
As far as I know, The static method you should use to avoid Memory Leak. Eg:
new Thread(new Runnable() {
#Override
public void run() {
// do something long here
YourActivity.this.doSomething();
}
})
--> above code will make your app get memory leak error when you close your app when the thread is running.
However, with new refactor you can avoid memory leak easily:
private static class MyRunnable implements Runnable {
WeakReference<YourActivity> activity;
#Override
public void run() {
// do something long
if(activity.get() != null){
activity.get().doSomething();
}
}
}
It is much easier to create several instances of an inner class (by calling its' constructor) than creating several instances of an anonymous class.
A much easier question to answer is How are Anonymous (inner) classes used in Java?, which in short is to either quickly implement an interface (or abstract class) without adding much functionality to the interface (or abstract class) vs. wanting a strongly typed sub-class of another class which which will be constructed regularly.
A good example for interfaces/abstract classes you'd usually want to use an anonymous inner class are Runnables and most Listener interfaces, since they only serve as a wrapper for a piece of code "given" to an instance of another class. Good examples for inner classes are Fragments in android or custom controls (View in android), though refactoring those into separate classes can make them much more reusable.
A quick and dirty test is "Do I need create my own constructor for my inner class?", if the answer is "yes" than use a non-anonymous inner class.

Publishing thread safe object [duplicate]

According to the Java Language Specification, constructors cannot be marked synchronized because other threads cannot see the object being created until the thread creating it has finished it. This seems a bit odd, because I can indeed have another thread view the object while it's being constructed:
public class Test {
public Test() {
final Test me = this;
new Thread() {
#Override
public void run() {
// ... Reference 'me,' the object being constructed
}
}.start();
}
}
I know that this is a pretty contrived example, but it seems in theory that someone could come up with a more realistic case where marking the constructor synchronized would be legitimate in order to prevent races with threads like this one.
My question is this: is there a reason that Java would specifically disallow the synchronized modifier on a constructor? Perhaps my above example is flawed, or perhaps there really is no reason and it's an arbitrary design decision. In either case, I'm really curious and would love to know the answer.
If you really need synchronization of the rest of the constructor versus any threads which anyhow gets a reference to your not-yet-totally-constructed object, you can use a synchronized-block:
public class Test {
public Test() {
final Test me = this;
synchronized(this) {
new Thread() {
#Override
public void run() {
// ... Reference 'me,' the object being constructed
synchronized(me) {
// do something dangerous with 'me'.
}
}
}.start();
// do something dangerous with this
}
}
}
Usually it is considered bad style to "give out" your not-yet-constructed object like this, so a synchronized constructor is not necessary.
In some corner cases a synchronized constructor would be useful. Here is a more realistic example, from the discussion of Bozho's answer:
public abstract class SuperClass {
public SuperClass() {
new Thread("evil") { public void run() {
doSomethingDangerous();
}}).start();
try {
Thread.sleep(5000);
}
catch(InterruptedException ex) { /* ignore */ }
}
public abstract void doSomethingDangerous();
}
public class SubClass extends SuperClass {
int number;
public SubClass () {
super();
number = 2;
}
public synchronized void doSomethingDangerous() {
if(number == 2) {
System.out.println("everything OK");
}
else {
System.out.println("we have a problem.");
}
}
}
We want that the doSomethingDangerous() method is only called after construction of our SubClass object is complete, e.g. we only want the "everything OK" output. But in this case, when you only can edit your SubClass, you have no chance of achieving this. If the constructor could be synchronized, it would solve the problem.
So, what we learn about this: never do something like I did here in the superclass constructor, if your class is not final - and don't call any non-final methods of your own class from your constructor.
The question has been raised on a discussion list used by the writers of the Java concurrent API and the Java Memory Model. Several answers were given, in particular Hans Boehm replied:
Some of us (myself included IIRC) actually argued during the Java memory model deliberations that synchronized constructors should be allowed. Now I could go either way on it. Client code shouldn't use races to communicate the reference, so it shouldn't matter. But if you don't trust the clients of [your class], I think synchronized constructors could possibly be useful. And that was much of the reasoning behind final field semantics. [...] As David said, you can use synchronized blocks.
Because synchronized guarantees that actions on the same objects are not to be performed by multiple threads. And when the constructor is called you still don't have the object. It is logically impossible for two threads to access the constructor of the same object.
In your example, even if a method is invoked by the new thread, it is no longer about the constructor - it is about the target method being synchronized or not.
Constructor Modifiers section in JLS clearly says
There is no practical need for a constructor to be synchronized, because it would
lock the object under construction, which is normally not made available to other
threads until all constructors for the object have completed their work.
So there is no need for constructor to be synchronized.
Also it is not recommended to give out the objects reference(this) before object is created. One of the possible ambiguous situations would be to give out the objects reference is superclass constructor when subsclass object is being created.
In your example, the constructor is only actually called once from one thread.
Yes, it is possible to get a reference to an incompletely constructed Object (some discussions around double check locking and why it is broken reveal this problem), however, not by calling the constructor a second time.
Syncronized on the constructor would prevent two threads from calling the constructor on the same Object simultaneously, and that is not possible, as it is never possible to call the constructor on an object instance twice, period.
I see little reason to forbid constructors to be synchronized. It would be useful in many scenarios in multi-threaded applications. If I understand the Java Memory Model correctly (I read http://jeremymanson.blogspot.se/2008/11/what-volatile-means-in-java.html) the following simple class could have benefited from a synchronized constructor.
public class A {
private int myInt;
public /*synchronized*/ A() {
myInt = 3;
}
public synchronized void print() {
System.out.println(myInt);
}
}
In theory, I believe a call to print() could print "0". This could happen if an instance of A is created by Thread 1, the reference to the instance is shared with Thread 2, and Thread 2 calls print(). If there is no special synchronization between the write myInt = 3 of Thread 1 and the read of the same field by Thread 2, Thread 2 is not guaranteed to see the write.
A synchronized constructor would fix this issue. Am I right about this?
The following code can achieve the expected result for synchronized constructor.
public class SynchronisedConstructor implements Runnable {
private int myInt;
/*synchronized*/ static {
System.out.println("Within static block");
}
public SynchronisedConstructor(){
super();
synchronized(this){
System.out.println("Within sync block in constructor");
myInt = 3;
}
}
#Override
public void run() {
print();
}
public synchronized void print() {
System.out.println(Thread.currentThread().getName());
System.out.println(myInt);
}
public static void main(String[] args) {
SynchronisedConstructor sc = new SynchronisedConstructor();
Thread t1 = new Thread(sc);
t1.setName("t1");
Thread t2 = new Thread(sc);
t2.setName("t2");
t1.start();
t2.start();
}
}
Such a synchronization might make sense in some very rare cases, but I guess, it's just not worth it:
you can always use a synchronized block instead
it'd support coding in a pretty strange way
on what should it synchronize? A constructor is a sort-of static method, it works on an object but gets called without it. So synchronizing on the class also makes (some) sense!
When in doubt, leave it out.
Note that constructors cannot be synchronized — using the synchronizedkeyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

What is the main advantage of extending Thread class (or when to extend Thread instead of implement runnable)

I'm trying to find out what are the possible advantages of extending the Thread class would be?
This is a part of another question which I describe:
There is two way of creating threads in Java
extending from Thread class
implementing the runnable interface
As expalined here there are several benefits of using runnable interface. My question is what is the advantage of extending from Thread class? The only advantage that comes to my mind is that one can extend from Thread class, and let's say call it ThreadExtended class. Then he/she can add more functionality in ThreadExtended(which I don't know what that might be), and then when he/she wants to create a thread, instead of extending from Thread class, it extends from ThreadExtended.
Is there any advantages in using Thread class instead of Runnable interface? Do you know any class(es) that extends from Thread class and then ask users to extends from those classes if they want to have multithreading capabilities?
public class ThreadExtended extends Thread{
//override some functions || add more functionality to Thread class
}
public class MyThread extends ThreadExtended{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Using ThreadExtended instead of Thread directly");
}
}
public static void main(String args[])
{
MyThread myThread = new MyThread();
myThread.start();
}
}
There is rarely a compelling reason to extend the Thread class. I would imagine that in most cases, you would end up just throwing all of your 'do some stuff' logic into the run method anyway.
You should definitely stick with implementing Runnable. By choosing to extend Thread, you are creating a class hierarchy that probably is nonsensical and will wind up restricting your options for refactoring things in the future. By choosing to implement Runnable, you make no demands of what the lineage of the implementer is, and you can use powerful abstractions like the ExecutorService to abstract away the nuts and bolts of running a chunk of code. Finally, preferring to implement an interface rather than extend a class is a good practice!
The only reason to extend Thread is if you need to add behavior that is associated with the thread itself, rather than the task that the thread is executing.
For example, if you're implementing a thread pool (which nobody should do anymore, given java.util.concurrent), you would need to change the behavior of the thread so that (1) it can accept new work, and (2) it returns itself to the pool. In a very simplified form:
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public void run() {
while (true) {
// wait on lock
try {
this.runnable.run();
}
catch (Throwable ex) {
// do something with exception
}
finally {
// return to pool
}
}
}
I find it clearer to extend Thread if I also configure the thread, for instance:
class FileReaper extends Thread {
FileReaper() {
setDaemon(true);
setName(getClass().getSimpleName());
}
#Override public void run() {
// do something
}
}
Simply put, when you extend Thread that will be the only class you will be extending from!
There is also a good reason to extend a Thread - if you want to create a Looper Thread:
This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
The UI thread is a Looper Thread, but you might want to create your own worker Looper Thread. To learn how the Thread with a Looper running its loop() method on it behaves, see my recent answer here.

How to synchronize access on a static field of a super class?

I have a class which contains a static field that acts like a singleton :
public class A {
private static MyAPI instance = null;
protected synchronized static MyAPI getAPI() throws Exception {
if (instance == null){
// init API;
}
return instance;
}
// other methods
}
And I have multiple classes which inherit from the class A and needs to perform actions on the API. I work in a multi-threaded environment and the API can work once at a time, so I have to ensure that all the subclasses don't work on the API at the same time. To do that, I synchronize the super class when I access the API in subclasses :
public class B extends A {
public void myMethod(){
synchronized (A.class) {
myAPI = getAPI();
// do stuffs with myAPI
}
}
}
With this solution, I lock the entire class instead of just the API instance, so the other methods of my class A are not available when a subclass work on the API and performances can be decreased.
Do you think this is the best solution or do you know a better way ?
Thanks.
There are two issues that I'd consider here:
First, because the MyAPI object acts as a singleton, the fact that other classes inherit from class A is irrelevant. You might as well just have other classes in a non-hierarchical structure refer to the singleton.
Secondly, the synchronization should be done inside the code of MyAPI, and this way you can control the synchronization granularity any way that you want. This lets you also achieve better encapsulation, and you don't need to worry about a bad-behaving caller who forgets to acquire a lock before proceeding. It can be per method, per functionality, etc.
For example:
class MyAPI {
public synchronized void doWork1() { // class level lock
...
}
public void doWork2 {
synchronized (someLockObject) {
...
}
}
public void doWork3 { // related to doWork2, lock the same object
synchronized (someLockObject) {
...
}
}
If you don't want to lock on the entire class, you may lock on a static object that you use only in that method:
public class A {
private static MyAPI instance = null;
protected static Object lockForMyMethod = new Object(); //have a static lock
// other methods
}
public class B extends A {
public void myMethod(){
synchronized (A.lockForMyMethod) { //do not lock on A.class
myAPI = getAPI();
// do stuffs with myAPI
}
}
}
Not sure why you need to lock down every access to your static member but consider using AtomicReference and it's getAndSet() method for better performance.
I work in a multi-threaded environment and the API can work once at a time, so I have to ensure that all the subclasses don't work on the API at the same time.
Depending on your environment, consider to use the ExecutorService.
For example: you could use a ThreadPoolExecutor with a fixed thread-pool size of 1 and submit your jobs to that executor.
That way you can ensure your API is only used within the call() method of the Callable you submitted.
Since you have only one thread working, you don't have to worry about concurrent access of the API.
Again, i don't know the environment you are working so maybe it is a bad idea or simple not possible to solve the problem with a ExecutorService.

Categories