How Python's garbage collection mechanism works?
This is an extremely broad question but a high-level overview is possible. First, we need to understand that the internal references are represented as graphs. Keeping this in mind, let's go through a few important points regarding garbage collection in python. 1) Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else 2) Occasionally things called "reference cycles" happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn't be live. But each of them has a reference count of 1. 3) Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first. Through these points we can get a bird eye's view of how the grabage collection mechanism works in python.
How many string objects are created in the snippet given below String s = new String("new");
On first glance, it may seem like a simple question. A single java statement with a new keyword. Obviously the answer has to be 1. Correct? No!! This is a little tricky question. Careful observation is needed to do this. So let's do it step by step. Firstly as we have found, a new keyword. So a string instance is being created. Now, what are the other sources of instance creation? Have a look at "new" part. What's a "new"? Yeah! It's a String. A non-mutable one. So in order to create a string instance s, we created a non-mutable String object which resides in the pool of non-mutable Strings in Java Virtual Machine. Therefore, the answer to this question is not 1 but 2. One is s, and the other is "new"
What is the risk in blocking the Main thread when performing a lengthy operation such as web access or heavy computation?
Android guidelines clearly specify that all the long-running operations should be done on a worker thread and not the Main thread which is also known as UI thread. But what happens if we don't follow that? Application Not responding exception will be thrown which will crash and restart the application. This happens when the UI doesn't respond in over 5 seconds. To avoid this, we have certain mechanisms build in the Android framework itself or we can use Java threading libraries too. These mechanisms are -> Java Threads - The plain old java threads. -> Andriod AsyncTask - Allows to do stuff in the background and do the results part in the UI thread. -> RxJava - Reactive techniques to handle asynchronous programming (Multithreaded programming)