Skip to main content

Posts

Showing posts from September, 2020

Synchronized Keyword in Java

In Java threading support, threads mostly communicate with each other via shared objects or shared member variables within the same object. Three type of complications can arise from this when multiple threads are allowed to access the same piece of memory. Thread Interference . Different threads access (read and write) the same data. This can lead to race conditions. The program behavior (what gets stored in the shared memory) depends on the order in which threads get access. This can cause non-deterministic behavior. Memory Consistency Errors . If multiple threads are updating the same variable, they can see a stale (inconsistent) value of a variable. Thread Contention . If locks are not used correctly, threads can get in each other's way, and slow down or sometimes even have to be killed by Java. Let's look at the first two problems. If two threads access the same variable, it is possible for them to get in each other's way. That is because Java might switch execution fr...

GoF patterns

Why learn GoF Design Patterns? Design patterns help you find out patterns in your code. It helps to visualize your code at a higher level and decompose it into logical units.   What are Design Patterns? Design patterns are canonical solutions to recurring problems. They are different from a library that is called from your code. Neither are they framework which is a complicated collection of libraries. Frameworks typically calls your code. The 24 design patterns covered in GoF book can be divided into three categories. Creational Patterns . These patterns seek to answer - "How should objects be created?".  Examples are - Factory, Abstract Factory, Singleton, Builder, Prototype, Dependency Injection. They usually seek to decouple the construction of an object from its use. There are advantages to doing this. Hide implementation of an object, only reveal its interface.  Defer instantiation until run-time.  Allow creation of finite number of instances.  Have f...