InterviewSolution
| 1. |
Best Practices while working with multi-threading in Java |
|
Answer» The most important usage of threads can be achieved USING Multithreading. This means that multiple tasks can run in parallel. Some of the best practices of multi-threading in Java are given as follows: 1. Minimize the locking scope The locking scope should be minimized as any code inside a lock cannot be executed concurrently and this REDUCES the application performance. 2. Concurrent Collections should be preferred over synchronized Collection Concurrent Collections should be preferred over synchronized Collections as they provide more scalability and performance. 3. Prefer Immutable Classes Immutable classes like String, Integer etc. as well as other wrapper classes should be used as they simplify the concurrent code writing. This is because there is no NEED to worry about the state. 4. Thread Pool Executors should be preferred instead of Threads A thread pool is a better option for a scalable Java application as thread creation is quite expensive. 5. Use Local Variables Instead of using class or instance variables, local variables should be used as much as possible. 6. BlockingQueue should be preferred for producer-consumer design The best way to implement the producer consumer design pattern is using BlockingQueue. This is quite important as many concurrency problems are based on the producer consumer design. 7. Synchronization utility should be preferred over wait notify There are a lot of synchronization utilities like CyclicBarrier, COUNTDOWNLATCH and Semaphore which should be used instead of wait and notify. 8. Use Semaphore to create bounds There should be bounds on different resources such as the file system ,database, sockets etc. to build a stable system. These bounds can be created using semaphores. |
|