<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vijay on Medium]]></title>
        <description><![CDATA[Stories by Vijay on Medium]]></description>
        <link>https://medium.com/@VijayBala_?source=rss-94a2c13ed5d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i0IW1GnBK8upxerEslPJpA.png</url>
            <title>Stories by Vijay on Medium</title>
            <link>https://medium.com/@VijayBala_?source=rss-94a2c13ed5d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:16:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@VijayBala_/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java Fundamentals: Part 1]]></title>
            <link>https://medium.com/@VijayBala_/java-fundamentals-part-1-b5babc8c735b?source=rss-94a2c13ed5d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5babc8c735b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vijay]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 23:53:21 GMT</pubDate>
            <atom:updated>2019-10-20T23:53:21.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Java is a powerful, general-purpose programming environment and one of the most widely used programming languages in the world. From it’s inception, designers of Java focused on creating a language paradigm that is <strong>simple</strong>, <strong>object-oriented</strong>, and <strong>platform independent</strong>. These are just some aspects of the language which often make it a preferred choice for developing cutting-edge, enterprise-level applications.</p><p>Java is considered a higher-level programming language that enables application developers to <strong>“write once, run anywhere” </strong>meaning that code written and compiled in a certain environment can run on all platforms regardless of computer architecture. Over the past twenty years, Java has remained a go-to language for use in projects of all sizes… now running on over three billion devices!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rr34BFSAkLv57ERrchJZdQ.png" /></figure><p>This post provides a brief look at the history of the programming language, and its’ key benefits to application developers. Core concepts around this topic are important to understand for any software engineer looking to learn and work with Java. Towards the end of this post, I’ve included a few of the most popular questions asked about this topic to aid in preparation for software engineering interviews.</p><h3><strong>What is Java?</strong></h3><p>The Java programming language was originally developed by Sun Microsystems, first released in 1995 as a core component of the company’s Java platform (Java 1.0 [J2SE]). James Gosling from Sun Microsystems, best known as the founder of Java, along with his team, began designing the first version primarily aimed at programming home appliances which are controlled by a wide variety of computer processors. Since its release, it has seen tremendous advancements in capabilities and as a result (to-date) — all Android apps are based on Java and 90 percent of Fortune 500 companies use Java as a server-side language for backend development. The language supports many configurations and is suitable for a variety of platforms including J2EE for Enterprise Applications, and J2ME for Mobile Applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*W0fxYQqSwQUIsMRzNre_8Q.png" /><figcaption>Language Version Timeline</figcaption></figure><p><strong>Key features that make Java great —</strong></p><ul><li><strong>Object-Oriented</strong> − In Java, everything is an Object. Java is robust and can be easily extended since it is based on the Object model.</li><li><strong>Platform Independent </strong>− Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine code, rather into platform independent bytecode. This bytecode can be distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.</li><li><strong>Multi-threaded </strong>− This key feature allows developers to write programs that can perform many tasks simultaneously. This design feature allows for the construction of interactive applications that can run concurrently while maximizing the utilization of computing resources.</li><li><strong>Interpreted</strong> − Java bytecode is translated on the fly to native machine instructions and is not stored anywhere. The development and deployment process can be more efficient and calculated since the linking is an incremental and light-weight process.</li><li><strong>High Performance </strong>− With the use of Just-In-Time compilers, Java enables high performance. The JIT compiler is the component that converts Java’s intermediate language into native machine code as needed.</li><li><strong>Memory Management </strong>— Java comes with a built-in garbage collector that automatically manages the memory used by programs.</li></ul><h3><strong>Java Platform</strong></h3><p>The platform required to develop and execute Java programs consists of three key components that are important to understand — the Java Development Kit (JDK), the Java Runtime Environment (JRE), and the Java Virtual Machine (JVM). The JDK consists of the JRE (and other development tools) which includes the JVM — the graphic below depicts the relationship between the three components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*kA1C-j4R1BA1fwnt.jpg" /></figure><p><strong>Breaking down components that make-up the platform —</strong></p><p><strong>Java Development Kit (JDK)</strong> — Composed of the tools required to compile, document, and package Java programs. This includes the JRE, an interpreter/class loader, a compiler, an archiver, and a documentation generator. Put simply, the JDK provides a complete toolkit for standard Java <strong>development</strong> and program <strong>execution</strong>.</p><p><strong>Java Runtime Environment (JRE) </strong>— Although it is included in the JDK, it is also available for use as a standalone component. The JRE provides the minimum requirements for <strong>executing</strong> a Java application but doesn’t include all features required for development; it consists of the JVM and the some core libraries which enable end-users to run Java applications.</p><p><strong>Java Virtual Machine (JVM) </strong>— The component responsible for executing the Java program line by line hence it is also known as a run-time <strong>interpreter</strong>. It interprets compiled Java bytecode for a computer’s hardware platform so that it can perform a Java program’s instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*tRyMCu3qO7x0vZnDsM5CnA.gif" /><figcaption>Java Program Workflow</figcaption></figure><p>The graphic above depicts the high-level workflow for developers’ looking to create and execute Java programs. <a href="https://www.geeksforgeeks.org/differences-jdk-jre-jvm"><strong><em>GeeksforGeeks</em></strong></a> is a great resource which provides additional details on the platform and how it works.</p><h3>Understanding Java Garbage Collection</h3><p>Java is object-oriented! It has a concept of object instances not raw bytes (in contrast to C), initializes object memory, has no pointer arithmetic and uses automatic memory management, called “garbage collection”. To optimize application execution, the JVM divides memory into <strong>stack </strong>and <strong>heap </strong>memory, put simply this is a built-in mechanism for both <strong>static </strong>and <strong>dynamic </strong>memory allocation. When Java programs run on the JVM, objects are created on the heap, and <strong>it’s the garbage collectors job to free up memory when these objects become unused.</strong></p><p><strong>Defining the Java Memory Models —</strong></p><p><strong>Stack Memory</strong> — Stores primitive values that are specific to a method and references to objects that are in a heap, referred from the method. When the method is finished execution, its’ corresponding stack frame is retired.</p><p><strong>Heap Memory —</strong> New objects are created in heap space and the references to these objects are stored in stack memory. Objects have global access and can be accessed from anywhere in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2m_--VDfzSjmyMzUByvvQ.png" /><figcaption><a href="https://www.baeldung.com/java-stack-heap">Memory Management in Java</a></figcaption></figure><p>The table above lists a summary of built-in capabilities, specific to each memory model. <a href="https://dzone.com/articles/java-memory-management">How does the garbage collector determine when and how to free up memory? Read all about it and more!</a></p><h3><strong>Interview Questions and Answers</strong></h3><p>The remainder of the post includes a collection of interview questions which aim to highlight the basic ideas that are most important to understand. Obviously, there is far more to the language than what is covered in this post but I’ve found the best approach (at least when starting out programming) is to build a breadth of understanding in a few key concepts and go from there.</p><p><strong>How is Java platform independent?</strong></p><ul><li>When you write Java code and compile it, a separate file is created for the converted source code, this file(with a .class extension) is known as “<strong>bytecode</strong>”. The main purpose of generating bytecode for a program is to achieve platform independence which allows code generated on one platform to be executed on another regardless of computer architecture.</li></ul><p>Check out <a href="https://www.atnyla.com/tutorial/c-c-and-java/1/165">this</a> resource for more information on how this differs from C, and C++!</p><p><strong>What is an Object?</strong></p><ul><li>An instance of a class is called an object. The object has state and behavior. Whenever the JVM reads the “<strong>new</strong>” keyword, it will create an instance of that class.</li></ul><p><strong>What is a Constructor?</strong></p><ul><li>When a <strong>new </strong>object is created in the program, a constructor (can have more than one) gets invoked corresponding to the class.</li><li>The constructor is a method which has the same name as the class name and defines the state of the object being created.</li></ul><p><strong>What are the primary Object Oriented Programming concepts?</strong></p><ul><li>Inheritance</li><li>Encapsulation</li><li>Polymorphism</li><li>Abstraction</li></ul><p>Read more about <a href="https://medium.com/@VijayBala_/java-fundamentals-part-2-3fe2d2a71e67">OOP</a>!</p><p><strong>What is the significance of the following Java code: <em>public static void main (String[] args)</em>?</strong></p><p>This is the line at which a program will start executing. All Java applications begin execution by calling the <strong>main </strong>method.</p><ul><li>The keyword <strong>public </strong>is an access specifier, which allows the programmer to control the visibility of class members.</li><li>The keyword <strong>static </strong>allows main to be called without having to instantiate a particular instance of the class.</li><li>The keyword <strong>void </strong>tells the compiler that the main method does not return a value.</li></ul><p><strong>At a high-level, describe how Java’s garbage collector works?</strong></p><p>The garbage collector’s job is to automate memory management as objects are created, referenced, and deemed no longer needed by a program.</p><p>The main component of the garbage collection process is a “mark and sweep algorithm”. So how does it work at a high-level?</p><ul><li>The garbage collector <strong>scans </strong>Java’s dynamic memory areas for objects that are <strong>referenced</strong>.</li><li><strong>Unreferenced </strong>objects are identified and <strong>marked</strong> as <strong>ready </strong>for garbage collection. Two common ways objects can become unreferenced is by nulling the reference to an instance, or by assigning a reference to another object.</li><li><strong>Marked </strong>objects are deleted, and memory is <strong>compacted</strong> by moving referenced objects with allocated memory together forming a contiguous block on the <strong>heap</strong>. This makes it easier to allocate memory to new objects as program execution continues.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*30JwXSD7ChvQwMGb.png" /><figcaption>Garbage Collection Algorithm</figcaption></figure><p>Congrats on making it this far! In summary, the focus of this post was to cover a few very <strong>important </strong>concepts and equip developers’ (current and future) with a baseline of understanding to aid in continued learning!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*rwUVj1_lHTxIBJ4I.gif" /></figure><p><strong>In this post we —</strong></p><ul><li><strong>Briefly looked at the history of the Java programming language</strong></li><li><strong>Highlighted the components that make-up the Java platform</strong></li><li><strong>Identified features which aid in making Java the most popular programming language around</strong></li><li><strong>Explained “garbage collection” - an extremely unique &amp; powerful memory management mechanism built-in to Java</strong></li></ul><p>Check out <a href="https://medium.com/@VijayBala_/java-fundamentals-part-2-3fe2d2a71e67">Java Fundamentals (Part 2)</a> for a continued dive into the Java programming language. The post looks at common data structures provided by the core Java libraries, as well as important keywords and concepts in object-oriented programming overall.</p><p><em>Note: The word </em><strong><em>platform </em></strong><em>was mentioned several times in this post when discussing the benefits of Java. A platform is essentially just a machine running an operating system — Check out the link below to learn more about it!</em></p><ul><li><a href="https://medium.com/@VijayBala_/important-topics-in-operating-systems-c961afb68187">Important Topics in Operating Systems</a></li></ul><p>And if you’d like, follow me here! I’ll be continuing to add content related to software engineering concepts. Soon-to-come is a practical look at <strong>multithreading, </strong>an overview of the <strong>software development lifecycle</strong> (SDLC), and a brief glimpse into <strong>Agile</strong> methodologies as they are applied in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5babc8c735b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important Topics in Operating Systems]]></title>
            <link>https://medium.com/@VijayBala_/important-topics-in-operating-systems-c961afb68187?source=rss-94a2c13ed5d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c961afb68187</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vijay]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 02:55:01 GMT</pubDate>
            <atom:updated>2019-10-20T23:51:32.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>Operating Systems — What every application programmer must know</h3><p>An operating system (OS) is a <strong>critical</strong> component found on many devices that contain a computer, this includes laptops, smartphones and video game consoles. <strong>A software engineer (at any level) should understand the basics of an operating system and have general knowledge of what’s going on under-the-hood of a computer.</strong></p><p>This post provides a general overview of various concepts with some of the more commonly asked interview questions about the topic. It is meant to serve as an informative introduction into operating systems, as well as assist in preparing for a software engineering role. All of the topics discussed in this document are implemented within some of the most popular types of operating systems seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*nDRbCic4-ibScjnNjnPskQ.jpeg" /><figcaption>Types of Operating Systems</figcaption></figure><h3>Fundamentals of an Operating System</h3><h4>What is the main purpose of an operating system?</h4><p>An operating system is the most important piece of software that runs on a computer. It <strong>manages the computer’s computational activities</strong> associated with the <strong>hardware and provides services for application-level programs</strong>. Functions of an operating system include resource allocation, file system management, memory management, and security.</p><p>At the core of every operating system is the kernel which performs the above functions (manages communication between hardware and software). <strong>An operating system converts the 1&#39;s and 0’s flowing around at the computer chip-level into human-readable graphics that can be seen and interacted with by a user</strong>. All user software needs to go through the operating system in order to make use of the hardware, whether it be a mouse-click or a complex Internet application feature. The OS coordinates access to the central processing unit (CPU), memory, and storage to ensure each program gets what it needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bbrjjos6PH3VX4oDHZopjg.png" /><figcaption>Basic Operating System Components</figcaption></figure><h4>What makes up an operating system?</h4><ol><li><strong>Process Management</strong></li></ol><p>A process is an instance of a program in execution. When we write a computer program in a text file (independent of the programming language or OS) and then execute the program, it becomes a process within the system which performs all the instructions defined in the program. Once the program is loaded into memory, and it becomes a process, the operating system creates a Process Control Block (PCB) for it. The PCB includes an integer identifying the process (PID), as well as several other pieces of information needed to keep track of it.</p><p>The image below shows the structure of a Process Control Block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*iRRLvW9or49SYRAm9HvR0Q.jpeg" /><figcaption>PCB</figcaption></figure><p><strong>Program counter</strong>: Pointer to the address of the next instruction to be executed for this process.</p><p><strong>CPU registers</strong>: Where the process needs to be stored for execution when in a running state.</p><p><strong>Memory Management Information</strong>: The page table, memory limitations, and the segment table depending on memory used by the OS.</p><p>The actual process (a program loaded into memory) is divided into four sections — <strong>stack</strong>, <strong>heap</strong>, <strong>text</strong>, and <strong>data</strong>. The image below shows a simplistic layout of a process inside memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*pplsGMeRKFcc0IHr1j3YwA.jpeg" /><figcaption>Process Layout</figcaption></figure><p><strong>2. Threads and Parallelism</strong></p><p>A thread a.k.a. a <strong>lightweight process</strong> is simply a flow of execution with its’ own program counter (to keep track of instructions), system registers (to store variables), and stack (to store execution history). Threads cannot exist outside of a process, and more specifically each thread belongs to exactly one process (several threads can exist within a single process depending on the processor). Some information is shared between threads such as code segments, data segments, and open files — this means that when one thread alters a code segment memory item, peer threads are aware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*-pCSw4fVX-Jp0gfpMi9rTg.jpeg" /><figcaption>Thread Layout</figcaption></figure><p><strong>Kernel</strong>-<strong>level </strong>threads drastically improve the performance of an operating system by reducing the overhead needed for various operations that would otherwise require many separate processes. In a similar regard,<strong> user-level </strong>threads have been successfully implemented in network servers, web servers, and mission-critical applications because they improve application performance via parallelism.</p><p><strong>What advantages do threads provide?</strong></p><ul><li>Threads minimize the context switching time.</li><li>Use of threads provides concurrency within a process.</li></ul><p><strong>What resources are shared between threads?</strong></p><ul><li>Threads share code, and data segments but each has its’ own stack. Threads have independent call stacks, however the <strong>memory </strong>in other thread stacks is still accessible (although not recommended). Threads also share the same memory space while separate processes do not.</li></ul><p><strong>3. Scheduling</strong></p><p>At it’s core this is a really simple concept… <strong>scheduling is the means in which work is allocated to resources for completion</strong>. “Work” can be a multitude of different tasks such as<strong> virtual</strong> computation elements like threads, and processes, which then need to be scheduled onto hardware resources such as processers, network links, and expansion cards.</p><p>Scheduling is primarily implemented to ensure that computer resources are kept busy (load balancing), and users are able to share system resources (i.e. CPU time, disk drives) affectively. <strong>The scheduler is a module in the operating system which selects the next jobs to be loaded into the system and the next process to execute.</strong></p><p><strong>Important scheduling concepts to understand —</strong></p><ul><li>Schedulers can be broken down into long-term, medium-term and short-term depending on the lifecycle for which the functions need to be performed.</li><li>Schedulers dictate what processes to run on a system, the degree of concurrency to be supported at any one time, and how the split between I/O intensive and CPU intensive processes is to be handled.</li><li>An I/O-bound process is one that spends more of its time doing I/O than it spends doing computations. A CPU-bound process, in contrast, generates I/O requests infrequently, using more of its time doing computations.</li><li>A dispatcher is a scheduling module that gives control of the CPU to the process selected by the short-term scheduler. It receives control in kernel mode as the result of an interrupt or system call.</li><li>Several algorithms exist for implementing scheduling (i.e. distributing resources among components which simultaneously and asynchronously request them.</li></ul><p><strong>The main function of scheduling in the operating system is to provide a mechanism for sharing CPU time amongst threads and processes.</strong></p><p><strong>4. Memory Management</strong></p><p>An extremely important function of an operating system is memory management. Memory management is the capability of an operating system to move processes back and forth between main memory (RAM) and disk.</p><p><strong><em>Quick refresher</em></strong><em>:</em></p><ul><li>A hard disk or “hard drive” is a physical set of magnetic discs that can hold several gigabytes of data. Disk space refers to how much space is available on the hard disk for storing files (i.e. save a document, or install a new program).</li><li>Memory refers to the random access memory (RAM) inside the computer. Physically it is a set of small chips known as memory modules which are used to store actively running programs on the computer. For example, when the computer boots up, the operating system’s interface and other start-up processes are loaded into main memory… another example is when you open a program like Microsoft Word.</li></ul><p>In the OS, memory management keeps track of every single memory location (both virtual and physical), whether allocated to a process or free. It checks how much memory is to be allocated to each process and decides when the process will get the memory. RAM can be accessed hundreds of times faster than the hard drive, which is why active processes are loaded into RAM, and this functionality is vital to an operating system.</p><p><strong>5. I/O Device Management</strong></p><p>Another important function of an operating system is to manage various I/O devices including mouse, keyboards, touch pad, disk drives, display adapters, USB devices, Bit-mapped screen, LED, Analog-to-digital converter, On/off switch, network connections, audio I/O, printers etc.</p><p>An <strong>I/O system</strong> is required to take an application I/O request and send it to the physical device, then take whatever response comes back from the device and send it to the application. The operating system provides a mechanism for the CPU to pass information to and from an I/O device. There are three approaches available to communicate between the CPU and a device: Special Instruction I/O, Memory-mapped I/O, Direct memory access (DMA).</p><p><strong>Other important components —</strong></p><p><strong>File System</strong></p><ul><li>File creation/deletion.</li><li>Support for hierarchical file systems</li><li>Update/retrieval operations: read, write, append, seek</li></ul><p><strong>Security</strong></p><ul><li>Resources — CPU cycles, memory, files, devices</li><li>Users — authentication, communication</li></ul><p><strong>User Interface</strong></p><ul><li>Character-Oriented shell — sh, bash, terminal</li><li>GUI — Windows, Linux</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*htdo6bIP2lDw8ZOE.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Scheduling_(computing)#/media/File:Simplified_Structure_of_the_Linux_Kernel.svg">Simplified Structure of the Linux Operating System</a></figcaption></figure><h3><strong>Interview Questions and Answers</strong></h3><p><strong>What is a deadlock?</strong></p><ul><li>A deadlock occurs when two or more processes all block one another from completing execution. Expanded slightly — a deadlock occurs when a process or thread enters a waiting state because a requested system resource is held by another waiting process, which in turn is waiting for another resource held by another waiting process. The concept is termed deadlocked because a process cannot continue execution until a resource is allocated to it.</li></ul><p><strong>How would you prevent a deadlock?</strong></p><ul><li>The technique for deadlock avoidance is to have a resource hierarchy. Make sure that all threads acquire locks to resources in the same order. This avoids the deadlock scenario where thread 1 holds lock A and needs lock B while thread 2 holds lock B and needs lock A. With a lock hierarchy, both threads would have to acquire the locks in the same order (i.e. A before B).</li><li>Strictly speaking, a mutex is <strong>locking mechanism</strong> used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there is ownership associated with mutex, and only the owner can release the lock (mutex).</li><li>Semaphore is <strong>signaling mechanism</strong> (“I am done, you can carry on” kind of signal). For example, if you are listening to music on your cellphone and at the same time your friend calls you, an interrupt is triggered upon which an interrupt service routine (ISR) signals the call processing task to wakeup.</li></ul><p>See the Dining Philosopher’s problem for a classic scenario that intelligently describes deadlock —</p><p><a href="http://adit.io/posts/2013-05-11-The-Dining-Philosophers-Problem-With-Ron-Swanson.html">The Dining Philosophers Problem With Ron Swanson</a></p><p><strong>When writing multi-threaded applications, one of the most common problems experienced are race conditions. What is a race condition?</strong></p><ul><li>Remember that two or more threads can access shared data… in the situation where both try to access a data segment at the same time, we refer to both threads as “racing” to access/change the data. Most thread scheduling algorithms can swap between threads at any time so the order in which the shared data will be accessed is unknown. The example below depicts a situation in which one thread is performing a “check-then-act”, but leaves open the possibility of another thread modifying something in the middle of the action.</li></ul><pre>if (x == 5) // The &quot;Check&quot; {    <br>   y = x * 2; // The &quot;Act&quot;</pre><pre>   // If another thread changed x in between &quot;if (x == 5)&quot; and<br>   // &quot;y = x * 2&quot; above, y will not be equal to 10. <br>}</pre><ul><li>The most common, and fail-safe method for preventing race conditions from occurring is to utilize a locking mechanism. Prior to performing the “check” act, we can utilize a lock or mutex to guard the resource from access by concurrent threads until a specific piece of code is executed. In the example below, “obtain lock” can be implemented programmatically in all a variety of ways.</li></ul><pre>// Obtain lock<br>if (x == 5) // The &quot;Check&quot; {    <br>   y = x * 2; // The &quot;Act&quot;<br>}<br>// Release lock</pre><ul><li>In <strong>Java</strong>, a locking mechanism can be implemented using the <strong>synchronized</strong> keyword. Java provides a way of creating threads and using a synchronization method so that only one thread can access the resource at an given time. All threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block executes and exists.</li></ul><pre>//This class&#39; shared object will be accessed by threads class Counter  implements Runnable{<br>    int c = 0;<br>    @Override     <br>    public void run() {         <br>        synchronized(this){<br>        // incrementing             <br>        c++;             <br>        System.out.println(Thread.currentThread().getName() + &quot;c&quot;)};<br>        }<br>    }<br>}</pre><pre>public class RaceConditionDemo{     <br>    public static void main(String[] args) {         <br>        Counter counter = new Counter();         <br>        Thread t1 = new Thread(counter, &quot;ThreadOne&quot;);         <br>        Thread t2 = new Thread(counter, &quot;ThreadTwo&quot;);         <br>        Thread t3 = new Thread(counter, &quot;ThreadThree&quot;);<br>        t1.start();<br>        t2.start();<br>        t3.start();<br>    }<br>}</pre><pre>Output:</pre><pre>ThreadTwo 1 <br>ThreadThree 1 <br>ThreadOne 1 </pre><p>In the simple example above, we are incrementing the integer “c” each time a thread starts. We wrap the functionality in a <strong>synchronized </strong>keyword to ensure the mutable objects in the code block are inaccessible by concurrent threads.</p><p>Internally Java uses a so called <em>monitor</em> also known as <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html">monitor lock or intrinsic lock</a> in order to manage synchronization. This monitor is bound to an object, e.g. when using synchronized methods each method share the same monitor of the corresponding object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*0djojM-GXec5bFM-" /></figure><p>If you’ve made it this far, congrats! In summary the purpose of this post was to highlight the basic components that make-up an operating system and provide an overview of it’s major functionalities.</p><p><strong>In this post we —</strong></p><ul><li><strong>Defined an operating system and dove into it’s key components</strong></li><li><strong>Provided an overview of processes and threads</strong></li><li><strong>Touched on race conditions — common points of error that developers’ must know how to handle</strong></li></ul><p>For continued learning — check out the links below for more information about important concepts as they relate to the Java programming language!</p><ul><li><a href="https://medium.com/@VijayBala_/java-fundamentals-part-2-3fe2d2a71e67">Java Fundamentals (Part 1)</a></li><li><a href="https://medium.com/@VijayBala_/java-fundamentals-part-2-3fe2d2a71e67">Java Fundamentals (Part 2)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c961afb68187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Fundamentals: Part 2]]></title>
            <link>https://medium.com/@VijayBala_/java-fundamentals-part-2-3fe2d2a71e67?source=rss-94a2c13ed5d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fe2d2a71e67</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Vijay]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 00:25:30 GMT</pubDate>
            <atom:updated>2019-10-20T23:54:23.807Z</atom:updated>
            <content:encoded><![CDATA[<p>This post highlights some of the most important aspects of Java programming. The keywords and concepts covered in this blog are not-only important to understand but <strong>practical</strong> and <strong>routinely</strong> <strong>appear in some form during interviews for software engineering positions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*8Au6QYi7tfdafaBQ.gif" /></figure><h3>Java Keywords and Concepts</h3><p><strong>final, finally, finalize</strong></p><p><strong><em>final</em></strong></p><ul><li>When you assign the final reserved keyword to a <strong>variable </strong>in Java, this prevents modification of its’ state once initialized. If a variable is declared as final, you cannot modify its’ value — the result if we were to try is an immediate Compile Time Error. When you assign the final keyword to a <strong>class</strong>, this disallows the class from being extended. When you assign the final keyword to a <strong>method</strong>, then it cannot be overridden.It is important to note that in the case that a class is declared as final, then by default all methods in the class are also final… variables however are not.</li></ul><p><strong><em>finally</em></strong></p><ul><li>The finally keyword is a reserved keyword that really functions exactly as it’s named. It is used in association with the try/catch block, and basically identifies a piece of code that always executes when the try block exists. It is code that is executed even if an unexpected exception (checked or unchecked) occurs. Common practice is to put cleanup code (i.e. close a file), or in a bigger picture — code that prevents resource leaks — in a finally block because the run-time system always executes the statements regardless of what happens in the try block.</li></ul><pre>try<br>        { <br>            int i = arr[4]; <br>                  <br>            // this statement will never execute <br>            // as exception is raised by above statement <br>            System.out.println(&quot;Inside try block&quot;); <br>        } <br>          <br>        catch(ArrayIndexOutOfBoundsException ex) <br>        { <br>            System.out.println(&quot;Exception caught in catch block&quot;); <br>        } <br>          <br>        finally<br>        { <br>            System.out.println(&quot;finally block executed&quot;); <br>        }</pre><p><strong><em>finalize</em></strong></p><ul><li>The root of all classes — Object. This class contains a finalize method, which gets invoked when the lifecycle of an object is coming to an end and the JVM figures out that a particular object should be garbage collected. The main purpose of a finalize() method is provide a piece of code which allows for the release of resources used by objects BEFORE they’re removed from memory. This method can serve as a safety net when other methods fail. However, there are several problems that exist when using the reserved keyword finalizer, without getting into the implementation details, just realize a few things…</li><li>No timing guarantee of method execution since garbage collection can occur at anytime</li><li>System resources are limited, not all code may be executed prior to a system crash</li><li>Performance hit due to the JVM having to work extra hard when dealing with objects containing a non-empty finalize()</li></ul><p><strong>What is meant by immutability and why is it important?</strong></p><ul><li>In Java, an object is immutable if its state cannot change after construction. Immutable objects provide the benefit of being Thread safe — they do not permit concurrent modifications of the same instance across several threads. Immutable objects can be passed around without fear they will be modified, and in the case that their is a modification in state, this results in a new instance.</li></ul><p><strong>Example of an Immutable Class</strong></p><ul><li>The most straightforward example of an immutable class in Java is the <strong>String. </strong>When you initialize a variable of the String type, that value is <strong>final</strong> by definition, and it cannot be modified. Operations such as trim(), substring(), and replace() ALWAYS return a new instance, and don’t affect the current instance.</li></ul><pre>String test = &quot;test&quot;;<br>test = &quot;changed&quot;; // Correct - reference points to new value</pre><pre>String test = &quot;test&quot;;<br>String testTrim = test.trim(); // Correct - new instance returned</pre><ul><li>Other examples from the JDK include the wrapper classes: Integer, Float, and Boolean — these classes create a new instance every time you attempt to modify them.</li></ul><p><strong>How to create an Immutable Class?</strong></p><p>There are a few rules that must be adhered to in order to create an immutable class…</p><p><strong>The whole point of an immutable class is to create an object that is safe from modification. Marking all fields as final means that they cannot be changed after initial construction.</strong></p><ul><li>Mark the class as final — no classes can extend it</li><li>Mark the fields as final — one-time initialization</li></ul><p><strong>Don’t expose setter methods…</strong></p><ul><li>If you would like to expose methods which allow modification of an object’s state, you must always return a new instance of the class.</li></ul><p><strong>Immutable classes can include mutable object references</strong></p><ul><li>If the class holds a mutable object, make sure to use a <strong>clone copy </strong>when modifying fields. This is simple. When we have an immutable class with a mutable object as a member variable, we will simply pass it into the constructor, the same as we do for all objects in OOP and additionally we will also create a new instance of that class. It is on the new instance that we will extract the parameters from the object provided as input, and set on the new instance. This is the <strong>clone copy</strong> method. Upon setting all fields of the cloned copy, we will than assign the new object to the instance field for the class, ensuring our entire class remains immutable.</li></ul><pre>public class ImmutableObject {<br>    private final int primitiveField;<br>    private final Object objectField;</pre><pre>public ImmutableObject(int p, Object o) {<br>        primitiveField = p;<br>        objectField = new Object(); // Clone <br>        objectField.setField(o.getField()); // Copy<br>    }</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8AumafDUfbcAnDGr.png" /></figure><h3>Object-Oriented Programming: Abstract classes vs. Interfaces</h3><p><strong>Abstract classes</strong> —</p><ul><li>An abstract class is a class which MUST contain one or more abstract methods. All this really means is that a class marked as “abstract” can contain “abstract” methods (methods with no implementation), and/or regular methods which do contain implementation details. The idea behind an abstract class is to provide a basic level of functionality across your class hierachy while also keeping in mind that operations may be performed differently for various classes. An abstract method is useful when we want to force subclasses to provide a custom implementation for it.</li></ul><p><strong>Interfaces</strong> —</p><ul><li>An interface is just like a class except that it can only contain method signatures and fields. A Java interface cannot contain implementation details of the method, only the signature (name, parameters, exceptions, return type). A class that implements an interface is required to provide implementation details for all methods of the interface. A Java class can implement multiple Java interfaces but remember this requires that the class implement all associated methods. Interfaces are a way of achieving polymorphism, a concept which implies that instances of a class (objects) can be used as if it were of different types.</li></ul><p><em>Main idea: An abstract class can contain unimplemented (abstract) and implemented methods which can be inherited from. An abstract class is extended. An interface simply serves as a contract, and cannot provide any method implementations. An interface is implemented.</em></p><h3>Data Structures in Java: Arrays vs. LinkedLists</h3><p><strong>Arrays —</strong></p><ul><li>An array is an object that contains a number of similarly typed variables. When we create an array, the JVM creates a contiguous block of memory with spaces in which the address of each member object may be stored. In the case of an array of objects, the heap contains an linear data structure which contains references to the values stored in the array. The array class is a member of the Java Collections Framework.</li></ul><p><strong>Big-O Worst-Case Performance</strong></p><p>Access: O(1), Search: O(n), Insertion: O(n), Deletion: O(n)</p><p><strong>LinkedLists —</strong></p><ul><li>Similar to an array, a linked list is a linear data structure but elements are not stored in contiguous locations and every element is a separate object with a value and an address. Each object is known as a node, and elements are linked using pointers and addresses. It provides advantages for insertions and deletions because of its’ dynamic nature which allows for updates to the head and tail of the list, while it has a few disadvantages with the major one being that nodes cannot be accessed directly. Access into the list requires that we need to start from one end of the list and traverse each link to reach our target node. A LinkedList is a member of the Java Collections Framework.</li></ul><p><strong>Big-O Worst-Case Run-Time Performance</strong></p><p>Access: O(n), Search: O(n), Insertion: O(1), Deletion: O(1)</p><p><strong>Sets —</strong></p><p>Just some things to remember:</p><ul><li>Does not allow duplicate values</li><li>Has no guaranteed internal order</li><li>Interface in the collections package</li><li>Concrete implementations include: HashSet, TreeSet, LinkedHashSet</li></ul><p><strong>Big-O Worst-Case Run-Time Performance</strong></p><p>Access: O(1), Search: O(n), Insertion: O(1), Deletion: O(1)</p><h3>Data Structures in Java: HashMaps</h3><p>One of the most useful data structures in all of programming is the HashMap. A HashMap implements the Map interface in the JDK and is used to store data in “key/value” pairs, in which one one object, a key (index) is used to access another object (a value). In contrast to an array which stores items in an ordered collection in which items are accessed with an index number, a HashMap allows for indexing via any class type.</p><p>Here is everything you need to know about a HashMap.</p><ul><li>Internally, a HashMap is just an array of single linked lists as elements.</li><li>A HashMap cannot contain duplicate keys</li><li>A HashMap can contain a null key and/or null value</li></ul><h4>Hash Functions and Hash Collisions</h4><p>When a user calls put(K key, V value) or get(Object key), the function computes the index of the bucket in which the entry should be. All this means is that the input key is passed to a function which computes a hashcode. This hashcode tells us where to place the value or where it is located. A <strong>hash collision </strong>occurs when a hash function returns the same bucket location for two different keys. Two different keys can be found to have the same hashCode in the case of two unequal objects in Java. HashMap uses the equals() and hashCode() methods to find the bucket location for a given input key. <strong>Remember </strong>that Java does guarantee that the same hash code will result for equal objects but not vice versa. Prior to Java 8, HashMaps handled collisions by using a linked list to store map entries which end up in the same array location. From Java 8 onwards, balanced trees are used in-place of linked lists when the size of the bucket grows beyond a certain threshold. Due to the tree properties, the worst case performance of retrieval operations improves from O(n) to O(logn).</p><p>Step by step:</p><pre>put(K key, Value v)<br>   hash(key) → hashcode<br>   index = hash &amp; (n-1) → index value</pre><p>When there is a collision, entries are appended to a linked list or balanced tree.</p><pre>get(Object key)<br>   hash(key) → hashcode<br>   index = hash &amp; (n-1) → index value</pre><p>use equals() to compare the hashcode of the given key with the hashcode of the key at the index value. If it matches then return the value, if it doesn’t then traverse the linked list or balanced tree at the index location until there is a match.</p><p><strong>Big-O Worst-Case Run-Time Performance</strong></p><p>Access: O(1), Search: O(1), Insertion: O(1), Deletion: O(1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WXVA4OjVwg_3QGH9.JPG" /><figcaption><a href="https://www.hackerearth.com/practice/notes/big-o-cheatsheet-series-data-structures-and-algorithms-with-thier-complexities-1">Big-O Runtime Cheat Sheet</a></figcaption></figure><h3>New Feature Introduced in Java 8</h3><h4>What is a default method and when should it be used?</h4><ul><li>In Java 8, interfaces support the addition of a “default” identifier on method declarations. Marking a method as default simply means that an implementation (filled in method body). This specifies a piece of code to be executed as the default in a situation where a concrete class fails to provide an implementation for that method.</li><li>The benefit of using a default methods is <strong>backwards compatibility</strong>. Default methods introduce a mechanism for adding functionality to an interface without breaking all classes that extend the interface. Think about it, when you add a method to an interface, all subclasses require an implementation for that method. when you add a method to an interface and identify it as default, subclasses CAN override the default implementation to extend the functionality or unconcerned classes can leave the method out and simply use the default behavior.</li></ul><p><strong>Why not use an abstract class?</strong></p><ul><li>Although this update in Java 8 does make it seem as though interfaces and abstract classes are the same… that is not the case. An abstract class can define a constructor. They can be objects with a state associated with them, in contrast to an interface which simply defines a contract. Methods in an abstract class can modify both method arguments as well as fields of their class, whereas default methods in an interface can only access its arguments because interfaces do not have any state. Both are really used for different purposes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*SkoDKBd2NbjpNe-T.gif" /></figure><p>If you’ve made it this far, congrats! In summary the purpose of this post was to highlight some of the more popular (and <strong>practical</strong>) aspects of the Java programming language.</p><p><strong>In this post we —</strong></p><ul><li><strong>Defined some Java keywords and capabilities related to immutability</strong></li><li><strong>Compared abstract classes and interfaces</strong></li><li><strong>Highlighted key data structures including arrays, lists, sets, and maps</strong></li><li><strong>Touched on the concept of “default” methods introduced in Java 8</strong></li></ul><p>Check out the links below to continue learning!</p><ul><li><a href="https://medium.com/@VijayBala_/java-fundamentals-part-2-3fe2d2a71e67">Java Fundamentals (Part 1)</a></li><li><a href="https://medium.com/@VijayBala_/important-topics-in-operating-systems-c961afb68187">Important Topics in Operating Systems</a></li></ul><p>And if you’d like, follow me here! I’ll be continuing to add content related to software engineering concepts. Soon-to-come is an overview of <strong>multithreading — </strong>a Java feature which allows concurrent execution of a program for maximum utilization of the CPU which is extremely beneficial in increasing performance for resource intensive applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fe2d2a71e67" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>