This document summarizes a Java hands-on workshop covering containers, I/O, reflection, generics and other Java concepts. The workshop included examples and exercises on topics like lists, sets, maps, iterators, object creation, garbage collection, the File class, readers/writers and more. Code examples were provided on GitHub for attendees to reference.
Performance van Java 8 en verder - Jeroen BorgersNLJUG
We weten allemaal dat de grootste verbetering die Java 8 brengt de ondersteuning voor lambda-expressies is. Dit introduceert functioneel programmeren in Java. Door het toevoegen van de Stream API wordt deze verbetering nog groter: iteratie kan nu intern worden afgehandeld door een bibliotheek, je kunt daarmee nu het beginsel "Tell, don’t ask" toepassen op collecties. Je kunt gewoon vertellen dat er een ??functie uitgevoerd moet worden op je verzameling, of vertellen dat dat parallel, door meerdere cores moet gebeuren. Maar wat betekent dit voor de prestaties van onze Java-toepassingen? Kunnen we nu meteen volledig al onze CPU-cores benutten om betere responstijden te krijgen? Hoe werken filter / map / reduce en parallele streams precies intern? Hoe wordt het Fork-Join framework hierin gebruikt? Zijn lambda's sneller dan inner klassen? - Al deze vragen worden beantwoord in deze sessie. Daarnaast introduceert Java 8 meer performance verbeteringen: tiered compilatie, PermGen verwijdering, java.time, Accumulators, Adders en Map verbeteringen. Ten slotte zullen we ook een kijkje nemen in de keuken van de geplande performance verbeteringen voor Java 9: benutting van GPU's, Value Types en arrays 2.0.
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...Maarten Balliauw
This document discusses .NET memory management and the garbage collector. It explains that the CLR manages memory in a heap and the garbage collector reclaims unused memory. It describes how objects are allocated in generations and discusses how to help the garbage collector perform better by reducing allocations, using value types when possible, and properly disposing of objects. The document also provides examples of hidden allocations and demonstrates tools for analyzing memory usage like ClrMD and dotMemory Unit.
Stream processing from single node to a clusterGal Marder
Building data pipelines shouldn't be so hard, you just need to choose the right tools for the task.
We will review Akka and Spark streaming, how they work and how to use them and when.
This session is all about - the mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
There are many programming languages that can be used on the JVM (Java, Scala, Groovy, Kotlin, ...). In this session, we'll outline the main differences between them and discuss advantages and disadvantages for each.
While the Java platform has gained notoriety in the last 15 years as a robust application platform with a thriving ecosystem and well-established practices, the Java language has had its share of criticism. Highly verbose, overly didactic, limited feature set; whichever flavor of criticism you prefer, it's patently obvious that Java is playing catch up to more modern languages with a less rigid evolution path.
The language landscape today is vastly different than it had been five or ten years ago; a wide array of languages are available, designed to suit a variety of flavors: Groovy, Clojure, Scala, Gosu, Kotlin... which should you choose? This lecture focuses on one company's decision to focus on Scala, and presents a case study based on our experiences using Scala in practice, in the hope of providing much-needed real world context to assist your decision.
This presentation was used for the Scala In Practice lecture at the Botzia Israeli Java User Group meeting, May 3rd 2012.
Performance van Java 8 en verder - Jeroen BorgersNLJUG
We weten allemaal dat de grootste verbetering die Java 8 brengt de ondersteuning voor lambda-expressies is. Dit introduceert functioneel programmeren in Java. Door het toevoegen van de Stream API wordt deze verbetering nog groter: iteratie kan nu intern worden afgehandeld door een bibliotheek, je kunt daarmee nu het beginsel "Tell, don’t ask" toepassen op collecties. Je kunt gewoon vertellen dat er een ??functie uitgevoerd moet worden op je verzameling, of vertellen dat dat parallel, door meerdere cores moet gebeuren. Maar wat betekent dit voor de prestaties van onze Java-toepassingen? Kunnen we nu meteen volledig al onze CPU-cores benutten om betere responstijden te krijgen? Hoe werken filter / map / reduce en parallele streams precies intern? Hoe wordt het Fork-Join framework hierin gebruikt? Zijn lambda's sneller dan inner klassen? - Al deze vragen worden beantwoord in deze sessie. Daarnaast introduceert Java 8 meer performance verbeteringen: tiered compilatie, PermGen verwijdering, java.time, Accumulators, Adders en Map verbeteringen. Ten slotte zullen we ook een kijkje nemen in de keuken van de geplande performance verbeteringen voor Java 9: benutting van GPU's, Value Types en arrays 2.0.
JetBrains Australia 2019 - Exploring .NET’s memory management – a trip down m...Maarten Balliauw
This document discusses .NET memory management and the garbage collector. It explains that the CLR manages memory in a heap and the garbage collector reclaims unused memory. It describes how objects are allocated in generations and discusses how to help the garbage collector perform better by reducing allocations, using value types when possible, and properly disposing of objects. The document also provides examples of hidden allocations and demonstrates tools for analyzing memory usage like ClrMD and dotMemory Unit.
Stream processing from single node to a clusterGal Marder
Building data pipelines shouldn't be so hard, you just need to choose the right tools for the task.
We will review Akka and Spark streaming, how they work and how to use them and when.
This session is all about - the mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
There are many programming languages that can be used on the JVM (Java, Scala, Groovy, Kotlin, ...). In this session, we'll outline the main differences between them and discuss advantages and disadvantages for each.
While the Java platform has gained notoriety in the last 15 years as a robust application platform with a thriving ecosystem and well-established practices, the Java language has had its share of criticism. Highly verbose, overly didactic, limited feature set; whichever flavor of criticism you prefer, it's patently obvious that Java is playing catch up to more modern languages with a less rigid evolution path.
The language landscape today is vastly different than it had been five or ten years ago; a wide array of languages are available, designed to suit a variety of flavors: Groovy, Clojure, Scala, Gosu, Kotlin... which should you choose? This lecture focuses on one company's decision to focus on Scala, and presents a case study based on our experiences using Scala in practice, in the hope of providing much-needed real world context to assist your decision.
This presentation was used for the Scala In Practice lecture at the Botzia Israeli Java User Group meeting, May 3rd 2012.
Quick introduction to Java Garbage Collector (JVM GC)Marcos García
The document discusses the Java Virtual Machine (JVM) and garbage collection. It describes the JVM memory areas like the heap, stack, method area and PC registers. It explains garbage collection techniques like minor and major GC used for young and old generation memory. The document also discusses different garbage collectors like serial, parallel, CMS and G1 collectors and how they perform compaction to reduce heap fragmentation. Tools for monitoring heap usage like jconsole and Websphere resource analyzer are also mentioned.
The document discusses several basic garbage collection techniques, including reference counting, mark-sweep collection, mark-compact collection, and copying garbage collection. Reference counting fails to reclaim circular structures and has overhead when pointers are created or destroyed. Mark-sweep identifies live objects but leaves memory fragmented, while mark-compact compacts objects after marking to reduce fragmentation. Copying garbage collection divides memory into two semispaces and copies live objects between them when one semispace fills up.
The document discusses Java garbage collection. It begins with an introduction to garbage collection, explaining that it is used to release unused memory and each JVM can implement its own garbage collection algorithms. It then covers the main garbage collection algorithms of reference counting, mark and sweep, and stop and copy. It also discusses finalize() methods, reference types in Java including strong, soft, weak and phantom references, and tips for improving garbage collection performance in Java programs.
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
Scala is a modern multi-paradigm programming language that integrates features of object-oriented and functional programming. It is statically typed, has a lightweight syntax, and compiles to Java bytecode so it can use Java libraries. Scala source code is compiled to Java bytecode using the Scala compiler and runs on the Java Virtual Machine. Common data structures in Scala include collections like lists, arrays, sets and maps. Scala supports higher-order functions, immutable data, pattern matching and case classes. Build tools like SBT are used to manage Scala projects.
Abstract –
Spark 2 is here, while Spark has been the leading cluster computation framework for severl years, its second version takes Spark to new heights. In this seminar, we will go over Spark internals and learn the new concepts of Spark 2 to create better scalable big data applications.
Target Audience
Architects, Java/Scala developers, Big Data engineers, team leaders
Prerequisites
Java/Scala knowledge and SQL knowledge
Contents:
- Spark internals
- Architecture
- RDD
- Shuffle explained
- Dataset API
- Spark SQL
- Spark Streaming
Understanding Java Garbage Collection - And What You Can Do About ItAzul Systems Inc.
Garbage collection is an integral but often misunderstood part of application behavior on Java platforms. As such, it is important for Java developers to understand how collector mechanisms work. This presentation reviews and classifies the major garbage collectors available in JVMs today. Following an overview of common garbage collection techniques such as generational, parallel, stop-the-world, incremental, and concurrent algorithms, it defines terms and metrics common to all collectors. It also discusses trade-offs in balancing requirements for responsiveness, throughput, space, and available memory and covers some pitfalls, common misconceptions, and garbage collection behavior myths.
This document discusses garbage collection in Java. It begins by explaining the motivation for garbage collection in Java, such as avoiding memory leaks and heap corruption. It then covers the goals of garbage collectors, including minimizing memory overhead, maximizing application throughput while keeping pause times low. Different types of garbage collectors are described, such as serial, parallel, CMS, and G1 collectors. Key concepts like generations, GC roots, and safe points are also summarized.
This is a talk I did for JavaOne 2009. The focus of the talk was memory management and system monitoring with freely available tools that are in the jdk or open source.
The document discusses Java garbage collection. It explains that Java's garbage collector automatically manages memory by freeing unreferenced objects. The garbage collector runs when memory is low to find and delete objects that cannot be reached. While garbage collection provides convenience, it has overhead as the system must pause current execution to run it which can influence user experience. The document also describes how objects are identified as garbage using tracing and reference counting collectors as well as how to explicitly make objects available for collection and finalize objects before deletion.
This document provides an overview of a 30-minute Scala tutorial covering Scala's core features like case classes, pattern matching, implicit classes, higher-order functions, and the Option monad. Scala is designed for concise syntax compared to Java, supports both object-oriented and functional programming, and is statically typed on the JVM. The tutorial demonstrates Scala concepts like implicit classes extending functionality, pattern matching for control flow, and using the Option monad to avoid null checks when chaining method calls.
Garbage collection is a form of automatic memory management used in computer programs to reclaim memory occupied by objects that are no longer needed. John McCarthy invented garbage collection for Lisp in 1959. Languages either use garbage collection or require manual memory management through techniques like allocating and freeing memory. Common garbage collection algorithms include reference counting, mark and sweep, and generational collection. The Java Virtual Machine uses different garbage collectors like serial, parallel, concurrent mark and sweep, and Garbage First collectors to reclaim memory in the Java heap.
Puppet is an IT automation tool that helps system administrators manage infrastructure through its lifecycle. It defines the desired state of systems in a declarative language and enforces that configuration by syncing resources. Resources are modeled as types with attributes and Puppet ensures resources match their defined state. Manifests declare resources and dependencies. Classes bundle resources and modules make reusable code and data available to any manifest. The master-agent architecture separates code from configuration enforcement.
This document discusses tuning garbage collection in the Java Virtual Machine. It describes key metrics for measuring garbage collection performance like throughput, footprint, and pause times. Factors that impact these metrics like generation sizing, survivor space ratios, and garbage collector selection are explained. The document also provides guidance on using JVM flags and garbage collection logs to analyze and improve performance.
Azul Product Manager Matt Schuetze's presentation on JVM memory details to the Philadelphia Java User Group.
This session dovetails with the March, 2014 PhillyJUG deep dive session topic focused on Java compiler code transformation and JVM runtime execution. That session exposes myths that Java is slow and Java uses too much memory. In this session we will take a deeper look at Java memory management. The dreaded Out of Memory (OOM) error is one problem. Garbage collector activity and spikes leading to long pauses is another. He covers the foundations of garbage collection and why historically Java gets a bad rap, even though GC provides a marvelous memory management paradigm.
This document discusses big Java heap sizes and garbage collection. It provides an overview of automatic memory management in Java and how the Java Virtual Machine (JVM) uses stop-the-world pauses for garbage collection. It also discusses tuning the garbage collection in the HotSpot JVM, including strategies for throughput versus low latency and options for the young and old generations.
This document describes a testing framework for analyzing Java garbage collection (GC) performance. It consists of:
1. A properties file that specifies test parameters like the GC algorithm, heap size, and object lifetimes.
2. A script file that defines the sequence of object creations and workload.
3. Classes that execute the script, measure GC performance, and write output to log files.
4. A script that iterates the tests, varying a property each time and analyzing the results.
Java Garbage Collection, Monitoring, and TuningCarol McDonald
The document discusses Java garbage collection. It explains that garbage collection automatically reclaims memory from objects that are no longer reachable to avoid memory leaks. It describes different garbage collection algorithms and strategies like generational and incremental garbage collection. It also discusses best practices and myths around memory management in Java.
Java is a relevant subject area taught in all computer science degree programs. This object-oriented computer language is used to write a variety of Software Applications.
The .NET Garbage Collector (GC) is really cool. It helps providing our applications with virtually unlimited memory, so we can focus on writing code instead of manually freeing up memory. But how does .NET manage that memory? What are hidden allocations? Are strings evil? It still matters to understand when and where memory is allocated. In this talk, we’ll go over the base concepts of .NET memory management and explore how .NET helps us and how we can help .NET – making our apps better. Expect profiling, Intermediate Language (IL), ClrMD and more!
This document provides an overview of key Java concepts including the Java Development Kit (JDK) and Java Runtime Environment (JRE), the Java Virtual Machine (JVM), data types in Java, operators, control statements like if/else and loops, classes and objects, encapsulation with access modifiers, inheritance with subclasses and superclasses, polymorphism through overloading and overriding, and hands-on experience with the command line, Eclipse, and Git. Contact information is provided at the end for Tejas Koundinya.
Quick introduction to Java Garbage Collector (JVM GC)Marcos García
The document discusses the Java Virtual Machine (JVM) and garbage collection. It describes the JVM memory areas like the heap, stack, method area and PC registers. It explains garbage collection techniques like minor and major GC used for young and old generation memory. The document also discusses different garbage collectors like serial, parallel, CMS and G1 collectors and how they perform compaction to reduce heap fragmentation. Tools for monitoring heap usage like jconsole and Websphere resource analyzer are also mentioned.
The document discusses several basic garbage collection techniques, including reference counting, mark-sweep collection, mark-compact collection, and copying garbage collection. Reference counting fails to reclaim circular structures and has overhead when pointers are created or destroyed. Mark-sweep identifies live objects but leaves memory fragmented, while mark-compact compacts objects after marking to reduce fragmentation. Copying garbage collection divides memory into two semispaces and copies live objects between them when one semispace fills up.
The document discusses Java garbage collection. It begins with an introduction to garbage collection, explaining that it is used to release unused memory and each JVM can implement its own garbage collection algorithms. It then covers the main garbage collection algorithms of reference counting, mark and sweep, and stop and copy. It also discusses finalize() methods, reference types in Java including strong, soft, weak and phantom references, and tips for improving garbage collection performance in Java programs.
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
Scala is a modern multi-paradigm programming language that integrates features of object-oriented and functional programming. It is statically typed, has a lightweight syntax, and compiles to Java bytecode so it can use Java libraries. Scala source code is compiled to Java bytecode using the Scala compiler and runs on the Java Virtual Machine. Common data structures in Scala include collections like lists, arrays, sets and maps. Scala supports higher-order functions, immutable data, pattern matching and case classes. Build tools like SBT are used to manage Scala projects.
Abstract –
Spark 2 is here, while Spark has been the leading cluster computation framework for severl years, its second version takes Spark to new heights. In this seminar, we will go over Spark internals and learn the new concepts of Spark 2 to create better scalable big data applications.
Target Audience
Architects, Java/Scala developers, Big Data engineers, team leaders
Prerequisites
Java/Scala knowledge and SQL knowledge
Contents:
- Spark internals
- Architecture
- RDD
- Shuffle explained
- Dataset API
- Spark SQL
- Spark Streaming
Understanding Java Garbage Collection - And What You Can Do About ItAzul Systems Inc.
Garbage collection is an integral but often misunderstood part of application behavior on Java platforms. As such, it is important for Java developers to understand how collector mechanisms work. This presentation reviews and classifies the major garbage collectors available in JVMs today. Following an overview of common garbage collection techniques such as generational, parallel, stop-the-world, incremental, and concurrent algorithms, it defines terms and metrics common to all collectors. It also discusses trade-offs in balancing requirements for responsiveness, throughput, space, and available memory and covers some pitfalls, common misconceptions, and garbage collection behavior myths.
This document discusses garbage collection in Java. It begins by explaining the motivation for garbage collection in Java, such as avoiding memory leaks and heap corruption. It then covers the goals of garbage collectors, including minimizing memory overhead, maximizing application throughput while keeping pause times low. Different types of garbage collectors are described, such as serial, parallel, CMS, and G1 collectors. Key concepts like generations, GC roots, and safe points are also summarized.
This is a talk I did for JavaOne 2009. The focus of the talk was memory management and system monitoring with freely available tools that are in the jdk or open source.
The document discusses Java garbage collection. It explains that Java's garbage collector automatically manages memory by freeing unreferenced objects. The garbage collector runs when memory is low to find and delete objects that cannot be reached. While garbage collection provides convenience, it has overhead as the system must pause current execution to run it which can influence user experience. The document also describes how objects are identified as garbage using tracing and reference counting collectors as well as how to explicitly make objects available for collection and finalize objects before deletion.
This document provides an overview of a 30-minute Scala tutorial covering Scala's core features like case classes, pattern matching, implicit classes, higher-order functions, and the Option monad. Scala is designed for concise syntax compared to Java, supports both object-oriented and functional programming, and is statically typed on the JVM. The tutorial demonstrates Scala concepts like implicit classes extending functionality, pattern matching for control flow, and using the Option monad to avoid null checks when chaining method calls.
Garbage collection is a form of automatic memory management used in computer programs to reclaim memory occupied by objects that are no longer needed. John McCarthy invented garbage collection for Lisp in 1959. Languages either use garbage collection or require manual memory management through techniques like allocating and freeing memory. Common garbage collection algorithms include reference counting, mark and sweep, and generational collection. The Java Virtual Machine uses different garbage collectors like serial, parallel, concurrent mark and sweep, and Garbage First collectors to reclaim memory in the Java heap.
Puppet is an IT automation tool that helps system administrators manage infrastructure through its lifecycle. It defines the desired state of systems in a declarative language and enforces that configuration by syncing resources. Resources are modeled as types with attributes and Puppet ensures resources match their defined state. Manifests declare resources and dependencies. Classes bundle resources and modules make reusable code and data available to any manifest. The master-agent architecture separates code from configuration enforcement.
This document discusses tuning garbage collection in the Java Virtual Machine. It describes key metrics for measuring garbage collection performance like throughput, footprint, and pause times. Factors that impact these metrics like generation sizing, survivor space ratios, and garbage collector selection are explained. The document also provides guidance on using JVM flags and garbage collection logs to analyze and improve performance.
Azul Product Manager Matt Schuetze's presentation on JVM memory details to the Philadelphia Java User Group.
This session dovetails with the March, 2014 PhillyJUG deep dive session topic focused on Java compiler code transformation and JVM runtime execution. That session exposes myths that Java is slow and Java uses too much memory. In this session we will take a deeper look at Java memory management. The dreaded Out of Memory (OOM) error is one problem. Garbage collector activity and spikes leading to long pauses is another. He covers the foundations of garbage collection and why historically Java gets a bad rap, even though GC provides a marvelous memory management paradigm.
This document discusses big Java heap sizes and garbage collection. It provides an overview of automatic memory management in Java and how the Java Virtual Machine (JVM) uses stop-the-world pauses for garbage collection. It also discusses tuning the garbage collection in the HotSpot JVM, including strategies for throughput versus low latency and options for the young and old generations.
This document describes a testing framework for analyzing Java garbage collection (GC) performance. It consists of:
1. A properties file that specifies test parameters like the GC algorithm, heap size, and object lifetimes.
2. A script file that defines the sequence of object creations and workload.
3. Classes that execute the script, measure GC performance, and write output to log files.
4. A script that iterates the tests, varying a property each time and analyzing the results.
Java Garbage Collection, Monitoring, and TuningCarol McDonald
The document discusses Java garbage collection. It explains that garbage collection automatically reclaims memory from objects that are no longer reachable to avoid memory leaks. It describes different garbage collection algorithms and strategies like generational and incremental garbage collection. It also discusses best practices and myths around memory management in Java.
Java is a relevant subject area taught in all computer science degree programs. This object-oriented computer language is used to write a variety of Software Applications.
The .NET Garbage Collector (GC) is really cool. It helps providing our applications with virtually unlimited memory, so we can focus on writing code instead of manually freeing up memory. But how does .NET manage that memory? What are hidden allocations? Are strings evil? It still matters to understand when and where memory is allocated. In this talk, we’ll go over the base concepts of .NET memory management and explore how .NET helps us and how we can help .NET – making our apps better. Expect profiling, Intermediate Language (IL), ClrMD and more!
This document provides an overview of key Java concepts including the Java Development Kit (JDK) and Java Runtime Environment (JRE), the Java Virtual Machine (JVM), data types in Java, operators, control statements like if/else and loops, classes and objects, encapsulation with access modifiers, inheritance with subclasses and superclasses, polymorphism through overloading and overriding, and hands-on experience with the command line, Eclipse, and Git. Contact information is provided at the end for Tejas Koundinya.
Best final year students IEEE PROJECTS Training center in coimbatore Tamilnadu| M.E, M.Tech,
BE, CSE, IT, MCA,MSC, BCA, JAVA, DOT NET, MATLAB, HADOOP, NS2, PHP| top 10 Final year project center coimbatore,
Best IEEE projects, internship projects in coimbatore,final year projects with internship in coimbatore Tamilnadu|final year 2016-2017 projects
Big data Hadoop projects, coimbatore gandhipuram Ram nagar project center,list of project center in coimbatore,bes training center in coimbatore
live project in coimbatore,real time project in coimbatore|j2ee training coimbatore,Real time project title with abstract
This document provides an overview of an Android development course for beginners from Udacity. The 6-week course covers building layouts using views like TextView and ImageView, making apps interactive using layouts like LinearLayout and RelativeLayout, and object-oriented programming. Key lessons include building the app structure and interface with XML, adding interactivity with buttons and listeners, and learning Java concepts like classes and objects. The goal is for students to gain foundational Android skills and build a simple calculator app by the end of the course.
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
Code is available at https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
Code is available at https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
This document discusses various programming paradigms and concurrency concepts in Java. It covers single and multi-process programming, multi-threading, processes, threads, synchronization, deadlocks, and strategies for designing objects to be thread-safe such as immutability, locking, and containment. It also summarizes high-level concurrency utilities in Java like locks, executors, concurrent collections, and atomic variables.
Presented at JavaOne 2013, Tuesday September 24.
"Data Modeling Patterns" co-created with Ian Robinson.
"Pitfalls and Anti-Patterns" created by Ian Robinson.
Concurrency refers to the execution of multiple instruction sequences simultaneously, as occurs when multiple process threads run in parallel on an operating system. Threads may communicate via shared memory or message passing. Concurrency is important in software that monitors real-world systems where many events occur simultaneously. Ensuring events are responded to in a timely manner while handling interactions between concurrent activities requires coordination techniques like concurrency control to avoid race conditions where state information is inconsistently modified by different threads.
This document provides an outline and overview of new features in Java 8. It discusses behavior parameterization through lambda expressions and method references, which allow passing behaviors as arguments in place of anonymous classes. It also covers the Stream API for functional-style processing of collections, Optional as an alternative to null, default methods to allow interfaces to evolve, and CompletableFuture for composable asynchronous programming. Finally, it notes some potential downsides of Java 8 like longer debugging with lambdas and limitations of its functional support.
This document discusses lambda expressions and functional interfaces in Java 8. It begins by providing examples of lambda expressions that act as anonymous implementations of interfaces with single abstract methods (SAM interfaces). It then explains various functional interfaces like Function, BiFunction, Consumer, Supplier, and Predicate that can be used with lambda expressions. The document emphasizes how lambda expressions allow removing unnecessary elements to focus on the essential parameters and body of an operation.
Apache Camel is swiss knife for integration architectural problems. A full implementation of EIP and Loaded with hundreds of components it is the de-facto standard in solving Integration problems.
Java 8 introduces new toolkit which enables new model of thinking for java developers – functional. It encourage us to rethink traditional approaches of Object Oriented programming which were commonly accepted for decades. In this talk we will review many Gang of Four design patterns showing how they can be re-implemented in more concise and often more simple and elegant ways. Also we will look beyond that and will see which new design patterns and programming technics functional thinking and new java toolkit bring for us.
Java Concurrency, Memory Model, and TrendsCarol McDonald
This document discusses concurrency in Java. It covers benefits and risks of threads, goals of concurrency utilities in Java, examples of executor services and thread pools, and best practices for thread safety including using immutable objects, atomic variables, and concurrent collections.
From java to android a security analysisPragati Rai
The document compares the security models of Java and Android. Both use sandboxing techniques like permissions and code signing to restrict apps. Java uses a virtual machine as a security boundary, while Android relies on Linux permissions and does not use its virtual machine for security. Both models aim to protect the host system from malicious code through install-time checks of an app's identity and resource requirements.
This document provides an overview of Android development for Java developers. It discusses Android software stacks, development tools, Google development references and tools, and includes examples of building a "Hello World" app, using XML for the UI, activities and fragments, intents, common views, list views and adapters, dialogs, toasts, the support library, and Google Play services. The presentation was given by Michael Hantler of FullStack Developers Israel on April 24th, 2014.
This document outlines an agenda for a mobile development camp workshop on Android development. The agenda includes introductions to Android architecture, building blocks like activities and intents, and best practices. It provides overviews and definitions of key Android concepts like the Dalvik VM, application lifecycles, and using intents to navigate between activities. Attendees will learn how to build their first basic Android application.
This document provides an overview of Java data structures including arrays, collections framework, and common collection interfaces like List, Set, and Map. It discusses how to use arrays to store and access data, the key methods of common collection interfaces, and hands-on exercises to work with arrays and collections in Java.
This document provides an overview of Java collections including:
- The various collection interfaces like List, Set, and Map.
- Concrete collection classes like ArrayList, LinkedList, HashSet, and HashMap.
- Best practices for using collections like coding to interfaces and choosing appropriate collections based on needs.
- Concepts like generics, iterators, Comparable and Comparators.
A collections framework provides a unified architecture for representing and manipulating collections of objects. It includes interfaces that define common operations on collections, implementations of those interfaces that provide reusable data structures, and algorithms that perform useful computations on collections. The main interfaces are Collection, Set, List, Queue, and Map. Collections make programming easier by reducing effort, increasing speed/quality, allowing interoperability, and fostering reuse.
This document discusses the main interfaces in the Java Collections Framework - List, Set, Map, Collection, Iterator and Queue. It describes the key characteristics of each interface and provides examples of common implementing classes. It also covers important utility methods from the Collections class for working with collections and choosing the appropriate collection implementation based on needs.
The document discusses Java strings, string buffers, file I/O, serialization, dates and numbers. Some key points include:
- String objects are immutable but string references are mutable. The String constant pool stores shared strings.
- StringBuilder is like StringBuffer but not thread-safe. Both are used for file I/O with large input streams.
- File handles file paths. FileReader/Writer read/write characters. BufferedReader/Writer improve performance.
- Serialization converts objects to streams. ObjectOutputStream writes and ObjectInputStream reads objects.
- Inheritance affects serialization if the superclass is serializable. Constructors don't run on deserialization.
- Calendar manipulates dates. Date
.NET UY Meetup 7 - CLR Memory by Fabian Alves.NET UY Meetup
The document discusses key concepts related to memory management in the .NET CLR, including the heap and stack, value and reference types, pointers, and how objects are allocated in memory. It explains the garbage collection process, including different flavors, generations of objects, and pinning. Large object heap and finalization are also covered as it relates to unmanaged resources. Overall, the document provides a comprehensive overview of memory management in the .NET CLR.
WHAT ARE COLLECTIONS?
Collections store arbitrary objects in a structured manner. Types of collections available within the .NET Framework are:
ARRAYS
ADVANCED COLLECTIONS -
i) Non - Generics
ii) Generics
This document provides an overview of key Java collection classes and interfaces. It discusses the Object class methods like toString(), equals(), hashCode(), and their contracts. It describes List, Set, Map, Queue interfaces and common implementations like ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap. It covers sorting, searching, converting between collections and arrays, and using iterators. TreeSet and TreeMap implement navigable set and map interfaces added in Java 6.
This document provides an introduction and overview of the Google Guava libraries. It describes what Guava is, why developers would use it, how it compares to Apache Commons libraries, its design principles and release cycles. It provides descriptions of some key Guava packages and classes for common Java utilities, including Preconditions, Optional, Objects, Strings, Charsets, CaseFormat, CharMatcher, Joiner and Splitter. The document aims to explain the purpose and usage of important Guava functionality.
This document discusses Java collections and arrays. It covers the Java.util package, interfaces in the collections framework like Set, List, Queue and Deque. It describes traversing collections with iterators and their methods. General purpose collection implementations like ArrayList, HashSet and HashMap are discussed. Arrays are compared to collections, noting that collections are dynamically sized while arrays are fixed size.
Mumbai Academics is Mumbai’s first dedicated Professional Training Center for Training with Spoke and hub model with Multiple verticles . The strong foundation of Mumbai Academics is laid by highly skilled and trained Professionals, carrying mission to provide industry level input to the freshers and highly skilled and trained Software Professionals/other professional to IT companies.
In this session you will learn:
Objects
Collections
Garbage Collection
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
Java is an object-oriented programming language developed by Sun Microsystems to be small, simple, and portable across platforms. It uses classes and objects, inheritance, interfaces, and packages. A class is a template that defines objects, which are instances of a class. Inheritance allows classes to inherit attributes and behaviors from parent classes. Interfaces define behaviors without implementations. Packages organize related classes.
This document provides an overview and examples of Java arrays, strings, string buffers, parameter passing, object constructors, modifiers like static and final, and defining constants. It discusses declaring and using arrays, bounds checking, copying and sorting arrays. It also covers initializing objects, using constructors, and destroying objects via garbage collection.
This document provides an overview and examples of Java arrays, strings, parameter passing, object constructors, and modifiers like static and final. It discusses declaring and using arrays, bounds checking, copying and sorting arrays. It also covers string and StringBuffer objects, passing parameters by value and reference, using constructors to initialize objects, and static and final modifiers to define constants and class methods.
This document provides an overview of various Java concepts including collections, exceptions, logging, and enums. Some key points covered include:
- Collections like List, Set, and Map are commonly used data structures in Java. The appropriate collection depends on the data type and requirements.
- Exceptions communicate errors and should follow best practices like specific exception types and avoiding null returns.
- Logging is important for debugging and monitoring. Logs should have readable messages in the correct severity type.
- Enums allow a variable to be a set of predefined constants and have benefits like type safety and singleton instances. Immutable objects are preferable unless mutability is explicitly needed.
The document discusses various collection types in Scala including their characteristics and examples. It covers the core collection traits like Traversable, Iterable and Seq as well as specific implementations like Vector, Stream, ArrayBuffer, Set, Map. It also discusses parallel collections which provide a high level abstraction to operate normal collections in parallel using the .par method.
The Scala programming language has been gaining significant traction over the last few years, being adopted by vastly different organizations from startups to large enterprises. While the language itself is pretty well understood and explained in tutorials and books, there is an apparent dearth of practical advice for new adopters on the best approach to integrating the new technology. In this talk I’ll attempt to offer such advice gathered over several years of production Scala use, focusing on tools, practices, patterns and the community, in the hope of making your transition into the Scala ecosystem easier and better-informed up front.
A talk given at JavaOne 2015 in San Francisco.
The document discusses Java 8 Streams, which provide a way to process data in a functional style. Streams allow operations like filter, map, and reduce to be performed lazily on collections, arrays, or I/O sources. The key aspects of streams are that they are lazy, support both sequential and parallel processing, and represent a sequence of values rather than storing them. The document provides examples of using intermediate operations like filter and map and terminal operations like forEach and collect. It also discusses spliterators, which drive streams and allow parallelization, and functional interfaces which are used with lambda expressions in streams.
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
What is Augmented Reality Image Trackingpavan998932
Augmented Reality (AR) Image Tracking is a technology that enables AR applications to recognize and track images in the real world, overlaying digital content onto them. This enhances the user's interaction with their environment by providing additional information and interactive elements directly tied to physical images.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemPeter Muessig
Learn about the latest innovations in and around OpenUI5/SAPUI5: UI5 Tooling, UI5 linter, UI5 Web Components, Web Components Integration, UI5 2.x, UI5 GenAI.
Recording:
https://www.youtube.com/live/MSdGLG2zLy8?si=INxBHTqkwHhxV5Ta&t=0
2. Examples & Exercises
The code for examples and exercises
related to the workshop can be found at
https://github.com/arpoladia/java-hands-on-workshop
3. Credits
Thinking In Java by Bruce Eckel
(http://www.mindviewinc.com/Books/TIJ4/)
Strongly recommend all Java programmers
to buy and read this book cover to cover
6. Basics
• There are two distinct concepts in containers represented as
interfaces – ‘Collection’ which is a sequence of individual
elements & ‘Map’ which is a group of key value pairs.
• There are three basic types of Collections - A ‘List’ holds elements
in the way they were inserted, a ‘Set’ cannot have duplicate
elements while a ‘Queue’ produces elements in a specific order.
• Java container classes are predefined generic classes. They also
resize themselves automatically, which gives a lot of flexibility.
7. List
• An ‘ArrayList’ excels at randomly accessing elements but is slower when
inserting and removing elements in the middle of the list.
• A ‘LinkedList’ provides fast sequential access and inexpensive insertions and
deletions in the middle of the list but is slower for random access.
• Some common methods with Lists are – contains(), add(), addAll(), remove(),
indexOf(), subList(), clear().
• LinkedList has extra methods which also allow it to be used as a stack or a
queue – getFirst(), addFirst(), removeFirst(), addLast(), removeLast().
• Example: ListOperations
8. Set
• A Set only allows one instance of each value i.e. it prevents
duplication.
• A HashSet uses a hashing function for lookup speed at the sacrifice of
order.
• A TreeSet keeps its elements sorted – either by the provided ordering
(through a Comparator) or by their natural ordering.
• A LinkedHashSet also uses hashing for lookup speed, but appears to
maintain elements in insertion order using an internal LinkedList.
• Example: SetTypes
9. Map
• A Map allows you associate a value with a key. Maps do not allow duplicate
keys. However, different keys can be associated to the same value.
• As we saw in Set, similarly we have HashMap, LinkedHashMap & TreeMap.
• Some common methods – get(), put(), putAll(), containsKey(),
containsValue(), keySet() etc.
• Maps (like Collections) can be easily expanded to multiple dimensions by
combining containers to create powerful data structures. For example –
Map<Brand, List<Product>>, Map<Person, Map<Brand, List<Product>>> &
so on.
• Example: MapTypes
10. Exercise
• Implement a program that uses Java’s Random class to generate
random integers between 0 to 10 and counts how many times
each integer was generated. Test the randomness for a varying
number of iterations.
11. Iterator
• Iterator is a light weight object used to move through a sequence without
worrying about its underlying structure or size. You can ask a collection to
hand you an iterator using iterator().
• You can check if the sequence has more objects by calling hasNext() on the
iterator. You can get the next object in the sequence by calling next().
• You can remove the last element returned by the iterator with remove().
• ListIterator is a more powerful subtype of Iterator produced only by List
classes that allows moving in both directions. It can also replace the last
element visited with set().
• Example: ListIteration
12. Container Taxonomy
Java SE 5 added –
• The Queue interface and its
implementations PriorityQueue & various
flavours of BlockingQueue.
• A ConcurrentMap interface and its
implementation ConcurrentHashMap for
use in concurrency.
• CopyOnWriteArrayList &
CopyOnWriteArraySet, also for use in
concurrency.
• EnumSet & EnumMap, special
implementations designed for use with
enums.
13. The equals() Method
A proper equals() must satisfy the following five conditions –
• Reflexive: For any x, x.equals(x) should return true.
• Symmetric: For any x & y, x.equals(y) should return true if and only if
y.equals(x) returns true.
• Transitive: For any x, y & z, if x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true.
• Consistent: For any x & y, multiple invocations of x.equals(y) should
consistently return true or consistently return false, provided theirs states
have not changed.
• Null-check: For any non-null x, x.equals(null) should return false.
14. Hashing And The hashcode() Method
• Hashed data structures internally use an array of ‘buckets’. From the key, a number
is derived that indexes into the array (points to a bucket). This number is the hash
code, produced by the hashcode() method.
• Each bucket in the array holds a list of map entries. These entries are searched in a
linear fashion using the equals() method.
• So instead of searching through all the entries, you quickly jump to a bucket where
you only have to compare a few entries, which is much faster.
• The hashcode() method must be fast, consistent and should result in an even
distribution of values. If the values tend to cluster, then the HashMap will be
heavily loaded in some buckets and performance will suffer.
• Example: EqualsAndHashcode
15. Choosing Between Implementations
• Choosing between Lists – ArrayList, LinkedList, CopyOnWriteArrayList
• Choosing between Sets – HashSet, LinkedHashSet, TreeSet, CopyOnWriteArraySet
• Choosing between Maps – HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap
• Example: ListPerformance, SetPerformance, MapPerformance
• Hashed containers performance – capacity and load factor.
• ‘Load factor’ is size/capacity. When the load factor is reached, the container expands by
roughly doubling the number of buckets and redistributing the existing objects into the
new set of buckets. This is called ‘rehashing’.
• Lower load factor means faster lookups but requires more space, while higher load factor
decreases the space required but increases the lookup cost.
17. Exercise
• Write a program that takes a sentence and returns the list of
unique words in the sentence, sorted alphabetically ignoring
case. It is expected that the same sentence may be passed
several times to the program. Since the operation can be time
consuming, the program should cache the results, so that when it
is given a sentence previously encountered, it will simply retrieve
the cached result.
19. Object Creation
• The first time an object of type T is created OR the first time a static method or
static field of class T is accessed, the Java interpreter locates T.class by searching
the classpath.
• As T.class is loaded, all of its static initializers are run. Static initialization take place
only once – during the first load.
• When you create a new T(), storage for a T object is allocated on the heap and
wiped to zero, automatically setting all primitives to their defaults and all
references to null.
• Next, any initializations that occur during field definition are executed. Finally, the
constructor is executed.
• Example: ObjectCreation
20. Garbage Collection
• Java heap is like a conveyor belt that moves forward every time
you allocate a new object, making it remarkably rapid.
• GC is based on the idea that all live objects must ultimately trace
back to a reference on the stack or in static storage.
• GC starts in the stack & static storage and walks through all the
references to find the live objects. For each reference, it traces
into that object and follows all it’s references and so on
(recursively) until it has found the entire web of live objects.
21. GC – Stop & Copy
• The program is first stopped, then each live object is copied from one
heap to another leaving behind all the garbage.
• In addition, as live objects are copied they are packed end-to-end
thereby compacting the new heap. Also, all the references that point
to the object are updated.
• One disadvantage is that it requires twice as much memory as
needed.
• Another disadvantage is that even if your program is generating little
to no garbage, the entire memory is copied which is wasteful.
22. GC – Mark & Sweep
• Each time a live object is found, it is ‘marked’ by setting a flag
in it, but nothing is collected yet.
• Only when the marking process is finished, the sweep
occurs. During the sweep, dead objects are released.
However, no copying happens – fragmented heap is
compacted by shuffling objects around.
• Only blocks created since last GC are compacted.
Periodically, a full sweep is made – all blocks are compacted.
23. GC – Adaptive Optimization
• JVM monitors the efficiency of GC.
• If it becomes a waste of time due to long-lived objects, JVM switches to
mark-and-sweep policy.
• Similarly, JVM tracks how successful mark-and-sweep is.
• If the heap starts to become fragmented, the JVM switches to stop-
and-copy policy.
• This is the ‘adaptive’ part of garbage collection in a JVM.
• Example: GarbageCollection (with different heap sizes).
25. The Class Object
• Run-time type information (RTTI) allows to discover and use type
information while a program is running.
• Type information is represented at runtime through a special object
called Class object. The Class object is used to create all regular
objects of your class.
• There is one Class object for each class that is a part of your program.
• A class object is just like any other object, so you can get a reference
to it. You can also constrain the type using generics.
• Example: ClassObject
26. Class Object Information
• getName() – fully qualified name, including the package
• getSimpleName() – only the class name, excluding the package
• getPackage() – get the package this type belongs to
• isInterface() – whether this type is an interface
• getInterfaces() – get the interfaces implemented by this type
• getSuperClass() – get the superclass of this type
• Example: ClassObjectInfo
27. Reflection
• Suppose you are given a reference to an object whose class is not
available at compile time. Or you need to create and execute objects
on a remote platform, across a network. These problems are solved
using reflection.
• The Class class supports reflection, in conjuction with java.lang.reflect
library which contains Field, Method, Constructor etc. You can use
Constructor to create new objects, Field to read and modify fields,
method to discover and invoke methods etc.
• Example: Reflection
28. A Note On Reflection
• You can change values of private fields by using setAccessible().
• You can even reach in and call private methods, using
setAccessible().
• Even private inner and anonymous classes cannot hide from
reflection.
• However, final fields are safe from change. You can try to change
the value using reflection and no error will be thrown, but nothing
happens – the value is not changed.
29. Exercise
• Create a class without any constructors. Verify that the compiler
creates a default constructor using reflection. Create a class that
has a single constructor that takes a single argument. Verify that
the compiler does not create any default constructor using
reflection.
• Create an ArrayList, print its size, add an element to it and again
print its size, performing all the above operations using
reflection.
31. Parameterized Types
• Generics implements the concept of parameterized types, which allows you
to write a class / interface that can work with multiple types.
• When you create an instance of a parameterized type, casts are taken care
of and type correctness is ensured at compile type.
• The most compelling example of generics are containers – List<>, Map<>,
Set<> etc.
• You substitute the actual type when you use the class / interface. You can
then only work with objects of the actual type or its subtypes.
• Example: TwoTuple, ThreeTuple
32. Generic Methods
• You can also parameterize methods within a class. The class itself
may or may not be generic – both are independent.
• To define a generic method, place a generic parameter list before
the return type – public <T> void add(T object) { }
• With generic method, you generally do not need to specify the
parameter type – the compiler can figure that out for you from
the arguments you pass. This is called ‘type argument inference’.
• Example: SetUtils, TupleUtils
33. Exercise
• Implement RandomList, a special type of parameterized list that
randomly selects one of its elements each time you call select().
• Implement a parameterized method that converts any given list
into a RandomList.
34. Erasure
• Although you can say ArrayList.class, you cannot say
ArrayList<String>.class. The truth is that there is no information about
generic parameter types available at runtime.
• Generics are implemented using ‘erasure’ – any type information is
erased when you use a generic. So List<String> & List<Integer> are in
fact, the same at runtime! Both are erased to their raw form List.
• Generic types are present only during static type checking – after
which they are erased by replacing with a non-generic type. List<T>
gets erased to List, T gets erased to Object and so on.
35. Erasure
• Because erasure removes type information, what matters at runtime are
the boundaries – the points where an object enters and leaves a method.
• These are the points where all the magic happens in generics during
compile time – extra type checks for the incoming values and inserted casts
for the outgoing values.
• Anything that requires knowledge of exact type at runtime will not work
with generics. For example - if (arg instanceof T), T var = new T(), T[] arr =
new T[10] - all will not work.
• Example: Erasure
36. Bounds
• Bounds allow you to place constraints on the parameter types
that can be used with generics. An important effect is that you
can call methods that are in your bound types.
• Bounds are defined using ‘extends’. The class must come first
and then the interfaces. You can have only concrete class but
multiple interfaces. For example - class Solid<T extends Class1 &
IF1 & IF2 & IF3>
• Example: Bounds
37. Exercise
• Implement a generic class Value that stores a value and keeps a
track of how many times the value is accessed by calling
getValue(). Implement a MFUList (most frequently used list) that
holds a list of Values and returns the most frequently used value
(first found by index) on calling mfuValue().
39. The File class
• The ‘File’ class can represent either a File or a Directory. The name is a
bit misleading as what it actually represents is a path on the file
system.
• Common methods –
• getPath(), getAbsolutePath(), getName(), getParent()
• exists(), canRead(), canWrite(), lastModified(), isFile(), isDirectory()
• renameTo(File), mkdir(), mkdirs(), delete()
• list()
• Example: FileInformation
40. Exercise
• Write a program that searches a given directory and lists all the
files and directories under it whose name contains the given
search query.
41. Reader & Writer
• InputStream & OutputStream (old) provide functionality in the form of
byte-oriented IO, whereas Reader & Writer provide Unicode-
compliant, character-based IO. They are also faster than the old
classes.
• Commonly used are FileReader, FileWriter, StringReader, StringWriter,
PipedReader, PipedWriter, BufferedReader, BufferedWriter.
• You’ll almost always want to wrap your reader & writer with a
BufferedReader & a BufferedWriter respectively – buffering tends to
dramatically increase the performance of IO operations.
• Example: FileReaderWriter
42. Exercise
• Write a program that reads an input file, counts the occurrence
of each character in the file, and writes these counts to an output
file.
43. Process Control
• Sometimes you may need to execute other operating system
programs / commands from inside Java. This is done using
java.lang.ProcessBuilder.
• The output of that program / command is available through
Process.getInputStream().
• Any program / command that you can execute from the terminal
can also be executed in this way.
• Example: OSCommand
44. NIO – New I/O
• The new I/O library, java.nio.*, introduced in JDK1.4 has one goal – speed. The old I/O
packages have been reimplemented using nio to take advantage of this speed, so you
will benefit even if you don’t explicitly use nio. The speed comes from using structures
that are closer to the operating system’s way of performing I/O – channels and buffers.
• Think of it as a coal mine – the channel is the mine containing coal (the data) and buffer
is the cart that you send into the mine. The cart comes back full of coal, you get the
coal from the cart. That is, you don’t interact directly with the channel but with the
buffer. The channel either pulls data from or puts data into the buffer.
• The buffer contains plain bytes and to turn them into characters, we must either
encode (while writing) or decode (while reading) – this is done using Charset.
• Example: FileChannelOperation
45. Exercise
• Modify the earlier program that reads an input file, counts the
occurrence of each character in the file, and writes these counts
to an output file using NIO library.
46. File Locking
• File locking allows you to synchronize access to a file as a shared
resource.
• The file locks are visible to and respected by the other operating
system processes because Java file locking mechanism maps directly
to the operating system’s native locking facility.
• You get a lock by calling tryLock() or lock() on a FileChannel. tryLock() is
non-blocking (it returns immediately) whereas lock() blocks until the
lock is acquired or the channel is closed. A lock is released using
FileLock.release().
• Example: FileLocking
48. Introduction to concurrency
• A program can be divided into multiple tasks distributed across
processors, which can dramatically improve throughput.
• One way to implement concurrency is through OS processes. Java
uses threading which creates tasks within the single OS process
represented by the executing process instead of forking additional
external processes.
• Each task is driven by a thread of execution. A thread is a single
sequential flow of control within a process.
• Java’s threading in pre-emptive, which means a scheduling mechanism
provides CPU time slices for each thread.
49. Basic Threading
• To define a task, simply implement Runnable and write a run() method to
make the task do your bidding. A task’s run() method usually has some loop
that continues until the task is no longer necessary, so you must establish
the condition on which to break out of the loop.
• To activate threading behaviour, you must attach the task to a Thread.
• You can optionally call Thread.yield() to yield control – it is basically a
message to the thread scheduler that says “I’ve finished my important parts,
now is a good time to switch to another task for a while”.
• To make the thread sleep or pause for a while, you can call TimeUnit.sleep().
• Example: BasicThreading
50. Executors
• Executors allows you to manage the execution of asynchronous tasks without
having to explicitly manage the lifecycle of threads. They are the preferred way
of working with tasks since its introduction in Java SE5.
• The CachedThreadPool creates one thread per task, whereas the
FixedThreadPool uses a fixed pool of threads to execute the submitted tasks.
• A SingleThreadExecutor is like a pool but with only one thread – it serializes
tasks and completes them in the order they were submitted.
• A call to ExecutorService.shutdown() prevents new tasks from being submitted
to it. All tasks that have already been submitted will be completed first and
then the program will exit.
• Example: UsingExecutors
51. Returning values from tasks
• If you want the task to produce a return value when it’s done, you can
implement Callable (instead of Runnable) and the call() method (instead of
run() method).
• Callable is a generic with a type parameter representing the return value
from call(). Such tasks are invoked using ExecutorService.submit(). The
submit produces a Future object parameterized to the same return type.
• You can query the Future with isDone() to see if the task has completed, and
call get() to fetch the result once the task is completed.
• Example: CallableTasks
52. Exercise
• Write a task which given a positive integer ‘n’, calculates and
returns the factorial of ‘n’ (factorial of a positive integer ‘n’ is the
product of n and all the positive integers less than n).
• Write a program which calculates and displays the factorial of the
first fifteen positive integers using a fixed pool of three threads.
53. synchronized keyword
• For concurrency to work, you need to prevent two tasks from accessing the same
resource during critical periods by putting a lock on it when a task is using it.
• One way is using ‘synchronized’ keyword. All objects automatically contain a single
lock called monitor. When you call a synchronized method, that object is locked
and no other synchronized method of that object can be executed until the lock is
released.
• It is important to make fields private otherwise synchronized keyword cannot
prevent another task from accessing a field directly.
• Every method that accesses a critical shared resource must be synchronized.
• Example: SynchronizingAndLockingAccess
54. Lock objects
• The java.util.concurrent library also contains explicit locking mechanism via
the use of Lock objects.
• The Lock object must be explicitly created, locked and unlocked.
• Right after you call lock(), you must place a try-finally block with the unlock()
in the finally clause – this is the only way to guarantee the lock is always
released.
• With the synchronized keyword, you can’t try and fail to acquire a lock, or try
to acquire a lock for a certain amount of time before giving up – this is
possible only using explicit Lock objects using the tryLock() method.
• Example: SynchronizingAndLockingAccess
55. volatile keyword
• The volatile keyword ensure visibility across the application. If
you declare a field as volatile, this means that as soon a write
occurs for that field, all reads will see the change.
• You should make a field volatile if that field could be
simultaneously accessed by multiple tasks, and at least one of
those accesses is a write.
• Volatile does not work if the value of a field depends on its
previous value (such a incrementing a counter) – you need to
synchronize in such cases.
56. Exercise
• Implement a generic class ConcurrentArrayList which is safe to
use in a multi-threaded environment. It should internally use an
ArrayList for storage and have five methods - get(index), add(),
remove(index), clear(), size().
57. Thread states
• A Thread can be in any of four states –
New : A thread remains in this state momentarily during creation when it performs
initialization. At this point it becomes eligible to receive CPU time. The thread
scheduler then transitions it to runnable or blocked state.
Runnable: This means a thread can be run when CPU cycles are available for it. It
might or might not be running, but nothing is preventing it from being run by the
scheduler i.e. it is not dead or blocked.
Blocked: The thread is prevented from being run due to some reason. It won’t
perform any operations until it re-enters the runnable state. The thread scheduler
simply skips threads in blocked state while allotting CPU time.
Dead: A thread in dead or terminated state is no longer runnable and will not
receive any CPU time, its task has completed.
58. Becoming blocked
• A thread can become blocked for the following reasons –
You’ve put it to sleep by calling sleep(), in which case it will
not be run for the specified time.
It is waiting for some I/O operation to complete.
It is trying to acquire a lock on another object (either by
calling a synchronized method or by trying lock() method)
and that lock is not available because it has already been
acquired by another task.