Posts

Showing posts with the label Java

Avoid Deadlock in Java

Image
  Java programming language supports multithreading. It involves multiple threads running simultaneously for multitasking. But in certain cases or due to certain shortcomings, the threads find themselves in the waiting state forever. In this article, We will understand the deadlock condition in Java and different ways to avoid it. The following are the topics discussed in this article: What is Deadlock in Java? Deadlock Example How To Avoid Deadlock in Java? What is Deadlock in Java? Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other. This usually happens when multiple threads need the same locks but obtain them in different orders. Multithreaded Programming in Java suffers from the deadlock situation because of the synchronized keyword. It causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Deadlock Example public class Example { public static void main(String[] args)

Java 8 Stream API

  Introduced in   Java 8   along with other programming features,   Stream API   provides various functionalities to process a collection of objects. Before we dive into Streams API, let’s see for an example, how we used to iterate a List and calculate the sum before the introduction of Streams in Java 8. List<Integer> numList = Arrays.asList(2,5,7,9,10,20,30,40); int sum = 0; Iterator<Integer> iterator = numList.iterator(); while (iterator.hasNext()) { int number = iterator.next(); if (number< 10) { sum += number; } } The above codes works perfectly fine and the variable sum will have the value 23 as the sum of numbers less than 10, but there are few issues with this code. The code has to be written on how the list should be iterated although the requirement is just to obtain the sum of the numbers which are less than 10 The program is sequential A lot of code must be written to perform this simple calculation. To avoid the above issues, Stream API was i