Android interview question Summary (2)

Source: Internet
Author: User
Tags finally block

Android interview question Summary (2)
Preface I have been looking for a job for almost two weeks since I recently resigned. During this time, I have learned the difference and depth of my knowledge about the technical concepts of Beijing, Shanghai, Guangzhou, and Western cities. as the saying goes: I am ashamed and brave. After the interview was abused, I also found my professional qualities and development plan for this year as a developer. as the saying goes, Wang Hou will be familiar with all kinds of things. I don't believe that I have taken every technical detail seriously from today on ., the city of Shenzhen has no land for me. well, chicken soup and nonsense are not enough, and the questions for today's interview are still recorded. bodyMeaning:An object no longer needs to be used, but its memory cannot be recycled because other objects hold the reference of this object.
Hazards:Only one, that is, the VM occupies too much memory, causing OOM (memory overflow) and program errors.
The main problems of Memory leakage can be divided into the following:Several Types:
1.Memory leakage caused by static variables:
In java, the lifecycle of static variables starts when classes are loaded and ends when classes are detached. in other words, in android, the lifecycle begins when the process starts and ends when the process dies. so during the running of the program, if the process is not killed, the static variable will always exist and will not be recycled. if a static variable strongly references a variable in an Activity, the activity will not be released, even if the activity executes onDestroy.
Solution:
1. Find an alternative object similar to the lifecycle of the static variable.
2. If not found, change the strong reference method to weak reference.
Case:Context Memory leakage caused by Singleton

public static IMManager getInstance(Context context) {        if (mInstance == null) {            synchronized (IMManager.class) {                if (mInstance == null)                    mInstance = new IMManager(context);            }        }        return mInstance;    }

When getInstance is called, if the input context is the Activity context. This Activity will not be released as long as the Singleton is not released.
Solution:Input the context of the Application.
2.Memory leakage caused by non-static internal classes:
In java, when a non-static internal class instance is created, its peripheral instance is referenced. if this non-static internal class instance does some time-consuming operations. the peripheral objects will not be recycled, resulting in Memory leakage.
Solution:
1.Change internal class to static internal class
After the internal class is changed to a static internal class, the reference of the external class object is no longer held. As a result, the program does not allow you to operate the activity object in handler, therefore, I need to add A weak reference to A/ctivity in handler );
Note: Why does the use of static internal classes not cause memory leakage?
A: static internal classes do not hold references to external objects.
2.If a property in Activity is strongly referenced, the reference method of the property is changed to weak reference.
Use WeakReference to wrap the object.
3.When the business permits the execution of onDestory, the activity ends these time-consuming tasks.

static class MyHandler extends Handler {    WeakReference mActivityReference;    MyHandler(Activity activity) {        mActivityReference= new WeakReference(activity);    }    @Override    public void handleMessage(Message msg) {        final Activity activity = mActivityReference.get();        if (activity != null) {            mImageView.setImageBitmap(mBitmap);        }    }}

3.Memory leakage caused by resource not closed
When resources such as BroadcastReceiver, Cursor, and Bitmap are used, they need to be released in time when they are not used. If they are not released, memory leakage may occur.

4. ** added: Solution for memory overflow when using Bitmap: ** 1. call the GC collection function of the System. gc (); 2. the size of the compressed image.

Summary

Although the differences between static and non-static classes are not great, Android Developers must understand them. at least we need to know that if an internal class instance has a longer life cycle than the Activity, we should never use non-static internal classes. the best practice is to use a static internal class, and then use weak references in the class to point to the Activity

2.Weak references, strong references, soft references, and virtual references Based on Java
StrongReference ):Is the most common reference. If an object has a strong reference, the GC recycler Will Never recycle it.

Object o = new Object (); // strongly reference public void test () {Object o = new Object (); // omit other operations}

When the memory is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally, and does not recycle strongly referenced objects to solve the problem of insufficient memory. when not in use, use the following method to weaken the reference.

There is a strong reference in the method. This reference is saved in the stack, and the actual reference content (Object) is saved in the heap. after this method is run, the method stack will be released. The reference of the referenced content does not exist and the Object will be recycled.

However, if this o is a global variable, We need to copy it to null when this object is not used, because the strong reference will not be garbage collected.
SoftReference ):If an object only has soft references, the memory space is sufficient and the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache.

String str = new String ("abc"); // strongly reference SoftReference
  
   
SoftRef = new SoftReference
   
    
(Str); // soft reference
   
  

Soft references can be used together with a ReferenceQueue. If the referenced objects are recycled by the garbage collector, the Java virtual machine adds this soft reference to the reference queue associated with it.
Weak reference:
The difference between weak references and soft references is that only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references.

    String str=new String("abc");          WeakReference
  
    abcWeakRef = new WeakReference
   
    (str);      str=null;    
   
  

When you want to reference an object, but this object has its own lifecycle, you do not want to intervene in the lifecycle of this object, at this time you are using weak references.
PhantomReference ):
As the name implies, "virtual references" are just the same as virtual ones, which are different from other types of references. Virtual references do not determine the object lifecycle. If an object only holds a virtual reference, it is the same as no reference and may be recycled by the garbage collector at any time.
Virtual references are used to track the activity of objects recycled by the garbage collector. A difference between virtual and soft references and weak references is that virtual references must be used together with the reference Queue (ReferenceQueue. When the garbage collector is preparing to recycle an object, if it finds that it has a virtual reference, it will add this virtual reference to the reference queue associated with it before it recycles the object's memory.

3.Keywords such as static and final in Java:
Static keywords:
The static modified member variables and member methods are independent of any object in the class. That is to say, it is shared by all instances of the class and does not depend on a specific instance of the class. As long as the class is loaded, the Java Virtual Machine can find them in the Method Area of the runtime data Zone according to the class name. Therefore, a static object can be accessed before any of its objects are created without referencing any objects.
1.Static modification method:
When the static keyword is used to modify a method, this method is called a static method. Static Methods belong to Classes rather than instance objects. So how do I call static methods? You can use the class name, method name, or instance object, or method name.
The method modified with the static keyword is loaded into the memory when the class is loaded. Is the class to which it belongs, not the instance.
It can be seen that this is not overwriting. In fact, static methods can only be hidden but not overwritten. When t1 is of the Person type, the static method of the Person class is called, because the static method only belongs to this class. When t2 is of the Test02 type, the static method of the subclass is called, when a subclass is not present, the method of the parent class is called to inherit the parent class.
2.Static attribute modification:
When the static property is modified, like the class, the class is loaded to the memory when the class is loaded.
3.Static Modifier
The block with static modification will also enter the memory as the class is loaded, so some static member variables can be initialized here.
4.Static considerations:
When a class is loaded by a virtual machine, the static member field and static statement block are initialized in the Declaration Order.
Static modified methods and variables only belong to the class, and all objects are shared.
Non-static member fields cannot be used in the methods and statement blocks modified by static.
Static members are not the characteristics of objects, but are only intended to find a place, so they need to be put into a class. it is meaningless to put "global variables" in the internal class, so they are prohibited.
Global variables cannot be defined directly in Java, but are implemented through static.
There is no const in Java and constants cannot be defined directly. It is implemented through static final.
Final keywords:
1.Use of final keywords:The referenced object and referenced object remain unchanged.
Modifier:*If a class is declared as final, it means that it cannot generate a new subclass and cannot be inherited as a parent class *. Therefore, a class cannot be declared as abstract final or interface final at the same time.
Modification method:Declare methods as final to ensure that they are not changed during use. Methods declared as final can only be used and cannot be overloaded. However, subclass can inherit the final method of the parent class.
Modifier variable:Indicates that the attribute value cannot be modified after the first initialization. The final attribute can be directly initialized or initialized in the constructor. If the attribute is directly initialized, its value cannot be modified by other functions (including constructor.
Modifier parameters:Parameter value cannot be modified
Local variables in the modifier:Local variables cannot be modified after the first initialization.
Note: The default value of any member variable declared in the interface is public static final.
Significance of Using final:
First, lock the method to prevent any inheritance class from changing its original meaning and implementation. When designing a program, you can do this if you want the behavior of a method to remain unchanged during the inheritance period and cannot be overwritten or rewritten.
Second, improve the efficiency of program execution. After a method is set to final, the compiler can put all calls to that method into "embedded" calls (embedded mechanism ).
Finally Keyword:
Finally blocks are provided for troubleshooting to clear any exceptions. If an exception is thrown, the matched catch clause is executed, and the control enters the finally block. So finally blocks will be executed.
The finally statement block is executed before the return statement in try or catch. More generally, the finally statement block should be executed before the transfer statement is controlled. In addition to return, the control transfer statement also includes break and continue. Return and throw hand control of the program to their callers (invoker), while control of break and continue is transferred within the current method.
Finalize method name:
The finalize () method is called before the Garbage Collector deletes an object.

4.Java multi-thread pool principle:

    public interface Executor {          void execute(Runnable command);      }  

Executors allows you to easily create a thread pool.
(1 ).NewCachedThreadPool:This thread pool is suitable for small tasks that can be completed quickly without a fixed size. It creates a thread for each task. So what is the difference between it and directly creating a Thread object (new Thread? Do you see the third and fourth parameters TimeUnit. SECONDS? The advantage is that the created thread can be reused within 60 seconds. The following is the source code of newCachedThreadPool () in Executors:

// Basic unbounded values (such as Integer. MAX_VALUE), allow the pool to adapt to any number of concurrent tasks public static ExecutorService newCachedThreadPool () {return new ThreadPoolExecutor (0, Integer. MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue
  
   
());}
  

(2 ).NewFixedThreadPool:The number of Thread objects used is limited. If the number of submitted tasks is greater than the maximum number of threads, these tasks will be queued, and when a Thread's task ends, the scheduling policy continues to wait for the next task to be executed. The following is the source code of newFixedThreadPool () in Executors:

    public static ExecutorService newFixedThreadPool(int nThreads) {            return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue
  
   ());        }  
  

(3 ).NewSingleThreadExecutor:It is the FixedThreadPool with a thread count of 1. If multiple tasks are submitted, these tasks will be queued and each task will end before the next task starts, all tasks use the same thread. The following is the source code of newSingleThreadExecutor () in Executors:

    public static ExecutorService newSingleThreadExecutor() {              return new FinalizableDelegatedExecutorService                  (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue
  
   ()));          }  
  

(4 ).NewScheduledThreadPool:Create a fixed-length thread pool and execute tasks in a delayed or scheduled manner.
ThreadPoolExecutor constructor:

Public ThreadPoolExecutor (int corePoolSize, // Core Thread int maximumPoolSize, // maximum number of threads maintained by the thread pool long keepAliveTime, // the idle time allowed by the thread pool maintenance thread TimeUnit, BlockingQueue
  
   
WorkQueue // blocking Queue) {this (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors. defaultThreadFactory (), defaultHandler );}
  

ExecutorService:To solve the lifecycle problem of the execution service, Executor extends the EecutorService interface and adds some methods for lifecycle management.

ThreadPoolExecutor thread pool implementation class:

Private final BlockingQueue
  
   
WorkQueue; // blocked queue private final ReentrantLock mainLock = new ReentrantLock (); // mutex lock private final HashSet
   
    
Workers = new HashSet
    
     
(); // Thread set. A Worker corresponds to a thread private final Condition termination = mainLock. newCondition (); // termination condition private int largestPoolSize; // The maximum number of threads in the thread pool that have been reached. Private long completedTaskCount; // number of completed tasks private volatile ThreadFactory threadFactory; // ThreadFactory object, used to create a thread. Private volatile RejectedExecutionHandler handler; // processing handle of the denial policy private volatile long keepAliveTime; // the idle time allowed by the thread pool maintenance thread private volatile boolean allowCoreThreadTimeOut; private volatile int corePoolSize; // The minimum number of threads maintained by the thread pool, even the idle private volatile int maximumPoolSize; // The maximum number of threads maintained by the thread pool
    
   
  

The priority of the processing task is:

Core Thread corePoolSize> task queue workQueue> maximum thread maximumPoolSize. If all three are full, handler is used to process rejected tasks. When the number of threads in the pool is greater than corePoolSize, excessive threads will wait for keepAliveTime for a long time. If no request is available, they will be destroyed by themselves.

WorkQueue:The Buffer Queue used by the thread pool. The length of the Buffer Queue determines the maximum number of buffers. There are three general policies for the Buffer Queue:
(1)Submit directlyThe default option of the work queue isSynchronousQueueIt directly submits tasks to the thread without holding them.
(2)Unbounded queue, The use of unbounded queues (for example, blockingqueue with no predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. In this way, the created thread will not exceed the corePoolSize. (Therefore, the value of maximumPoolSize is invalid .) When each task is completely independent from other tasks, that is, the task execution does not affect each other, it is applicable to the use of unbounded queues.
(3)Bounded queueWhen a limited maximumPoolSizes is used, a bounded Queue (such as ArrayBlockingQueue) helps prevent resource depletion, but it may be difficult to adjust and control. The queue size and the maximum pool size may have to be compromised: using large queues and small pools can minimize CPU usage, operating system resources, and context switching overhead, but may cause manual throughput reduction. If the tasks are frequently congested (for example, if they are I/O boundaries), the system may schedule a longer time than you permit for more threads. Using a small queue usually requires a large pool size, and the CPU usage is high, but it may encounter unacceptable scheduling overhead, which will also reduce the throughput.

ThreadFactory:Use ThreadFactory to create a new thread. Otherwise, Executors. defaultThreadFactory () is used to create threads in the same ThreadGroup, and these threads have the same NORM_PRIORITY priority and non-daemon status. By providing different ThreadFactory, you can change the thread name, thread group, priority, and daemon status. If ThreadFactory fails to create a thread when return null from newThread, the execution program continues to run, but cannot execute any tasks.
The ThreadFactory interface is implemented in the defathreadthreadfactory class and the defined methods are implemented as follows:

Static class defathreadthreadfactory implements ThreadFactory {private static final AtomicInteger poolNumber = new AtomicInteger (1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger (1); private final String namePrefix; defaultThreadFactory () {SecurityManager s = System. getSecurityManager (); group = (s! = Null )? S. getThreadGroup (): Thread. currentThread (). getThreadGroup (); namePrefix = "pool-" + poolNumber. getAndIncrement () + "-thread-";} // create a new task execution Thread public thread newThread (Runnable r) for the Thread pool) {// The task corresponding to the Thread is the Runnable object r Thread t = new Thread (group, r, namePrefix + threadNumber. getAndIncrement (), 0); // if (t. isDaemon () t. setDaemon (false); // sets the priority to Thread. NORM_PRIORITY if (t. getPriority ()! = Thread. NORM_PRIORITY) t. setPriority (Thread. NORM_PRIORITY); return t ;}}

RejectedExecutionHandler:
When Executor is disabled (executorService is executed. after the shutdown () method), and the Executor uses the finite boundary for the maximum thread and working queue capacity, and when it is saturated, new tasks submitted in the method execute () will be rejected.
In the above case, the execute method will call its RejectedExecutionHandler's RejectedExecutionHandler. rejectedExecution (java. lang. Runnable, java. util. concurrent. ThreadPoolExecutor) method. The following provides four predefined handler policies:

1) when the default ThreadPoolExecutor. AbortPolicy handler is rejected, the runtime RejectedExecutionException will be thrown;
2) The execute itself that runs the task is called in the ThreadPoolExecutor. CallerRunsPolicy thread. This policy provides a simple feedback control mechanism to speed down the submission of new tasks.

3) tasks that cannot be executed in ThreadPoolExecutor. DiscardPolicy will be deleted;

4) In ThreadPoolExecutor. DiscardOldestPolicy, if the execution program is not closed, the task in the Job Queue header will be deleted, and then retry the execution Program (if the execution fails again, repeat the process ).

By default, the thread pool adopts the defaultHandler policy.
The Callable interface indicates a piece of code that can call and return results. The Future interface indicates an asynchronous task, which is the Future result of an unfinished task. Therefore, Callable is used to generate results, and Future is used to obtain results.

The following content is from http://www.trinea.cn/android/java-android-thread-pool.
Disadvantages of new Thread:
A. Poor performance of each new object created by the new Thread.
B. There is a lack of unified management of threads, there may be no restrictions on new threads, competition between them, and the possibility of occupying too much system resources leading to crashes or oom.
C. Lack of more functions, such as scheduled execution, regular execution, and thread interruption.
Advantages of four thread pools provided by Java:
A. reuse existing threads to reduce the overhead of object creation and elimination, and improve performance.
B. It can effectively control the maximum number of concurrent threads, improve the usage of system resources, and avoid excessive resource competition and congestion.
C. provides scheduled execution, regular execution, single thread, concurrency control, and other functions.
(1 ).NewCachedThreadPool
Create a cache thread pool. If the thread pool length exceeds the processing requirement, free threads can be recycled flexibly. If no thread pool can be recycled, a new thread is created. The thread pool is infinite. When the second task is executed and the first task is completed, the thread for executing the first task is reused instead of creating a new thread each time.
(2 ).NewFixedThreadPool
Create a fixed-length thread pool to control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue. It is best to set the size of the fixed-length thread pool based on system resources. For example, Runtime. getRuntime (). availableProcessors ().
(3)NewScheduledThreadPool
Creates a fixed-length thread pool that supports scheduled and periodic task execution. Example code of delayed execution:
(4 ),NewSingleThreadExecutor
Create a single-threaded thread pool. It only uses a unique worker thread to execute tasks and ensures that all tasks are executed in the specified order (FIFO, LIFO, priority. Currently, most GUI programs are single-threaded. A single thread in Android can be used for operations such as database operations, file operations, batch installation of applications, batch deletion of applications, and other operations that are not suitable for merging and sending but may be IO obstructive and affect the UI thread response.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.