The Executor framework in Java provides a way to asynchronously execute tasks (implemented as Runnable or Callable interfaces) by submitting them to an ExecutorService which manages a pool of threads. This allows tasks to be executed concurrently without needing to explicitly manage threads. The framework provides factory methods like newFixedThreadPool to create ExecutorServices with different policies for executing tasks using threads from the pool. ExecutorServices also allow obtaining Future objects to asynchronously retrieve results from Callable tasks.
Concurrency on the JVM showing the nuts and bolts of Akka (I presume .. it's not first-hand stuff I'm saying, just speculating). Java Memory Model, Thread Pools, Actors and the likes of that will be covered.
Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java. The following article will cover all the popular Java interview questions for freshers as well as experienced candidates in depth.
Go through all the questions to enhance your chances of performing well in the interviews. The questions will revolve around the basic and core fundamentals of Java.
So, let’s dive deep into the plethora of useful interview questions on Java.
Lecture 13 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
The document discusses Java interview questions and answers. It covers topics like the differences between JDK, JRE and JVM, memory areas allocated by JVM, just-in-time compiler, Java platform vs other platforms, classloaders, access modifiers in Java, JDBC, Java API, encapsulation, inheritance, polymorphism and more. A total of 30 questions are presented along with detailed explanations for each.
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
The document provides an overview of modern Java concurrency. It discusses how concurrency has become important for performance as CPUs evolved to include multiple cores. It summarizes the java.util.concurrent utilities and common concurrency constructs like locks, queues, thread pools. It advocates using higher-level concurrency abstractions and more immutable and thread-safe collections to make concurrent programming easier.
Java Faqs useful for freshers and experiencedyearninginjava
1. The document discusses the differences between abstract classes and interfaces in Java. Abstract classes can contain implemented methods while interfaces contain no implementation code. A class can extend only one abstract class but implement multiple interfaces.
2. It defines checked and unchecked exceptions in Java. Checked exceptions must be caught or declared to be thrown, while unchecked exceptions like NullPointerException do not require handling.
3. User-defined exceptions can be created by extending the Exception class and using throw statements. The throw statement signals the exception and catch handles it.
- The document discusses multithreading concepts in Java like thread life cycle, creating threads, thread synchronization, and inter-thread communication.
- It explains that threads are lightweight subprocesses that share memory space for better efficiency compared to processes. Threads can run concurrently to achieve multitasking.
- The key methods for working with threads are discussed including start(), sleep(), join(), getName(), setName() and currentThread().
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples and demos for all cases discussed will be added to my blog www.javajee.com.
This document discusses multithreading in Java. It begins by explaining the difference between single-threaded and multithreaded programs. A multithreaded program contains two or more threads that can run concurrently. Each thread defines a separate path of execution. The document then covers key aspects of multithreading like creating threads by extending the Thread class or implementing the Runnable interface, starting and controlling threads, thread priorities, synchronization, and inter-thread communication.
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingSachintha Gunasena
This session discusses a basic high-level introduction to concurrency programming with Java which include:
programming basics, OOP concepts, concurrency, concurrent programming, parallel computing, concurrent vs parallel, why concurrency, real world example, terms, Moore's Law, Amdahl's Law, types of parallel computation, MIMD Variants, shared memory model, distributed memory model, client server model, scoop mechanism, scoop preview - a sequential program, in a concurrent setting - using scoop, programming then & now, sequential programming, concurrent programming,
Java Course 12: XML & XSL, Web & ServletsAnton Keks
This document provides an overview of XML, XSL, and Java technologies for working with XML. It discusses XML syntax and structure, validation, namespaces, DTDs and XML Schema for validation. It also covers XPath for querying XML, XSLT for transforming XML, and Java APIs including JAXP, JDOM, DOM4J, and JAXB for processing XML using Java.
Learn JAVA tutorial -This Java tutorial is specially prepared for the Beginners who wants to learn Java programming language from the basics. This tutorial is prepared by Easy Web Solutions by PSK Technologies located in Nagpur that provides best training in Java,PHP,Web Development Hardware and Networking and also provide Internship on all mentioned courses
This presentation introduces the concept of synchronization beatween threads, as implemented in the Java platform. It is the first part of a series of slides dedicated to thread synchronization. This slides introduces the following concepts:
- Thread safety
- Types of race conditions
- Locking (reentrant locks, intrinsic locks, synchronized blocks)
- Locking pitfalls
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
The document discusses JPA/Hibernate, object-relational mapping, and web services. It defines Hibernate as an open source ORM for Java that makes data persistent by storing it in a database. It notes that Hibernate automatically generates SQL queries and reduces development time compared to manually handling data with JDBC. The architecture of Hibernate and web services is described, including how Hibernate sits between code and the database to map objects to tables. Common web service types like SOAP and REST are also summarized.
This document contains a list of core Java interview questions and answers. Some key points:
- Threads enter a waiting state on I/O so that other threads can execute while I/O operations are performed.
- The List interface represents an ordered collection of objects.
- yield() returns a thread to the ready state, while sleep() places a thread in the not ready state for a specified time period.
- Wrapper classes allow primitive data types to be accessed as objects.
The Java Memory Model defines rules for how threads interact through shared memory in Java. It specifies rules for atomicity, ordering, and visibility of memory operations. The JMM provides guarantees for code safety while allowing compiler optimizations. It defines a happens-before ordering of instructions. The ordering rules and visibility rules ensure threads see updates from other threads as expected. The JMM implementation inserts memory barriers as needed to maintain the rules on different hardware platforms.
- Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. It runs on a variety of platforms such as Windows, Mac OS, and UNIX.
- The Java Virtual Machine (JVM) allows Java code to run on different platforms, as the bytecode is interpreted by the JVM rather than being compiled into platform-specific machine code.
- Some key features of Java include being object-oriented, platform independent, robust, interpreted, and multi-threaded.
Here is an example of inheritance in Java:
```java
class Employee {
String name;
int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
}
class Programmer extends Employee {
String language;
public Programmer(String name, int id, String language) {
super(name, id);
this.language = language;
}
}
```
Here Employee is the base/super class and Programmer is the derived/sub class that inherits from Employee. Programmer extends Employee and uses super() to pass values to the Employee constructor.
Java Course 7: Text processing, Charsets & EncodingsAnton Keks
Lecture 7 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
Do you know the difference between charset & encoding? Every programmer nowadays MUST understand these terms, how they work, and how to use them. Otherwise we constantly face broken software refusing to work with international characters properly.
To avoid name clashing, we can access classes using their fully qualified names like:
pack1.Student student1;
pack2.Student student2;
53 Rajeev Gupta
Session-2
Inheritance
Type of inheritance
Diamond problem
InstanceOf operator
Final, Abstract classes and interface
Acess control: public, private,protected and default
Packages
Abstract class
Interface
54 Rajeev Gupta
Inheritance
Java assigns each thread a priority that determines how that thread should be treated for the others. Thread priorities are integers that specify the relative importance of one thread to another.
A priority is meaningless as an absolute value; a higher priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next.
This document contains 55 questions and answers related to core Java concepts. Some key topics covered include threads and concurrency (questions 3, 5, 39), exceptions (question 41), collections and generics (questions 13, 15, 19), and GUI components and layouts (questions 2, 9, 10). The questions cover a wide range of fundamental Java topics for interview purposes.
This document discusses programming techniques for low-latency Java applications. It begins by explaining what low-latency means and when it is needed. It then covers various techniques including: using concurrent flows and minimizing context switches; exchanging data between threads via queues instead of shared memory; preallocating objects to avoid allocations; and directly accessing serialized data instead of object instances. The document also discusses memory issues like garbage collection pauses and cache line contention. It covers alternatives for accessing native code like JNA, JNI, and shared memory. Critical JNI is presented as a faster option than regular JNI.
Robust and Scalable Concurrent Programming: Lesson from the TrenchesSangjin Lee
The document discusses patterns for lazy initialization in concurrent programming. It presents the naive lazy initialization approach, which is not thread-safe, and several attempted fixes that have issues. A better approach is eager initialization, where the instance is initialized during static initialization for thread safety and no performance penalty of synchronization. For non-singletons, the holder pattern provides a thread-safe lazy initialization approach.
What are some of the performance implications of using lambdas and what strategies can be used to address these. When might be want an alternative to using a lambda and how can we design our APIs to be flexible in this regard. What are the principles of writing low latency code in Java? How do we tune and optimize our code for low latency? When don’t we optimize our code? Where does the JVM help and where does it get in our way? How does this apply to lambdas? How can we design our APIs to use lambdas and minimize garbage?
- The document discusses multithreading concepts in Java like thread life cycle, creating threads, thread synchronization, and inter-thread communication.
- It explains that threads are lightweight subprocesses that share memory space for better efficiency compared to processes. Threads can run concurrently to achieve multitasking.
- The key methods for working with threads are discussed including start(), sleep(), join(), getName(), setName() and currentThread().
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples and demos for all cases discussed will be added to my blog www.javajee.com.
This document discusses multithreading in Java. It begins by explaining the difference between single-threaded and multithreaded programs. A multithreaded program contains two or more threads that can run concurrently. Each thread defines a separate path of execution. The document then covers key aspects of multithreading like creating threads by extending the Thread class or implementing the Runnable interface, starting and controlling threads, thread priorities, synchronization, and inter-thread communication.
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingSachintha Gunasena
This session discusses a basic high-level introduction to concurrency programming with Java which include:
programming basics, OOP concepts, concurrency, concurrent programming, parallel computing, concurrent vs parallel, why concurrency, real world example, terms, Moore's Law, Amdahl's Law, types of parallel computation, MIMD Variants, shared memory model, distributed memory model, client server model, scoop mechanism, scoop preview - a sequential program, in a concurrent setting - using scoop, programming then & now, sequential programming, concurrent programming,
Java Course 12: XML & XSL, Web & ServletsAnton Keks
This document provides an overview of XML, XSL, and Java technologies for working with XML. It discusses XML syntax and structure, validation, namespaces, DTDs and XML Schema for validation. It also covers XPath for querying XML, XSLT for transforming XML, and Java APIs including JAXP, JDOM, DOM4J, and JAXB for processing XML using Java.
Learn JAVA tutorial -This Java tutorial is specially prepared for the Beginners who wants to learn Java programming language from the basics. This tutorial is prepared by Easy Web Solutions by PSK Technologies located in Nagpur that provides best training in Java,PHP,Web Development Hardware and Networking and also provide Internship on all mentioned courses
This presentation introduces the concept of synchronization beatween threads, as implemented in the Java platform. It is the first part of a series of slides dedicated to thread synchronization. This slides introduces the following concepts:
- Thread safety
- Types of race conditions
- Locking (reentrant locks, intrinsic locks, synchronized blocks)
- Locking pitfalls
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
The document discusses JPA/Hibernate, object-relational mapping, and web services. It defines Hibernate as an open source ORM for Java that makes data persistent by storing it in a database. It notes that Hibernate automatically generates SQL queries and reduces development time compared to manually handling data with JDBC. The architecture of Hibernate and web services is described, including how Hibernate sits between code and the database to map objects to tables. Common web service types like SOAP and REST are also summarized.
This document contains a list of core Java interview questions and answers. Some key points:
- Threads enter a waiting state on I/O so that other threads can execute while I/O operations are performed.
- The List interface represents an ordered collection of objects.
- yield() returns a thread to the ready state, while sleep() places a thread in the not ready state for a specified time period.
- Wrapper classes allow primitive data types to be accessed as objects.
The Java Memory Model defines rules for how threads interact through shared memory in Java. It specifies rules for atomicity, ordering, and visibility of memory operations. The JMM provides guarantees for code safety while allowing compiler optimizations. It defines a happens-before ordering of instructions. The ordering rules and visibility rules ensure threads see updates from other threads as expected. The JMM implementation inserts memory barriers as needed to maintain the rules on different hardware platforms.
- Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. It runs on a variety of platforms such as Windows, Mac OS, and UNIX.
- The Java Virtual Machine (JVM) allows Java code to run on different platforms, as the bytecode is interpreted by the JVM rather than being compiled into platform-specific machine code.
- Some key features of Java include being object-oriented, platform independent, robust, interpreted, and multi-threaded.
Here is an example of inheritance in Java:
```java
class Employee {
String name;
int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
}
class Programmer extends Employee {
String language;
public Programmer(String name, int id, String language) {
super(name, id);
this.language = language;
}
}
```
Here Employee is the base/super class and Programmer is the derived/sub class that inherits from Employee. Programmer extends Employee and uses super() to pass values to the Employee constructor.
Java Course 7: Text processing, Charsets & EncodingsAnton Keks
Lecture 7 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
Do you know the difference between charset & encoding? Every programmer nowadays MUST understand these terms, how they work, and how to use them. Otherwise we constantly face broken software refusing to work with international characters properly.
To avoid name clashing, we can access classes using their fully qualified names like:
pack1.Student student1;
pack2.Student student2;
53 Rajeev Gupta
Session-2
Inheritance
Type of inheritance
Diamond problem
InstanceOf operator
Final, Abstract classes and interface
Acess control: public, private,protected and default
Packages
Abstract class
Interface
54 Rajeev Gupta
Inheritance
Java assigns each thread a priority that determines how that thread should be treated for the others. Thread priorities are integers that specify the relative importance of one thread to another.
A priority is meaningless as an absolute value; a higher priority thread does not run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to next.
This document contains 55 questions and answers related to core Java concepts. Some key topics covered include threads and concurrency (questions 3, 5, 39), exceptions (question 41), collections and generics (questions 13, 15, 19), and GUI components and layouts (questions 2, 9, 10). The questions cover a wide range of fundamental Java topics for interview purposes.
This document discusses programming techniques for low-latency Java applications. It begins by explaining what low-latency means and when it is needed. It then covers various techniques including: using concurrent flows and minimizing context switches; exchanging data between threads via queues instead of shared memory; preallocating objects to avoid allocations; and directly accessing serialized data instead of object instances. The document also discusses memory issues like garbage collection pauses and cache line contention. It covers alternatives for accessing native code like JNA, JNI, and shared memory. Critical JNI is presented as a faster option than regular JNI.
Robust and Scalable Concurrent Programming: Lesson from the TrenchesSangjin Lee
The document discusses patterns for lazy initialization in concurrent programming. It presents the naive lazy initialization approach, which is not thread-safe, and several attempted fixes that have issues. A better approach is eager initialization, where the instance is initialized during static initialization for thread safety and no performance penalty of synchronization. For non-singletons, the holder pattern provides a thread-safe lazy initialization approach.
What are some of the performance implications of using lambdas and what strategies can be used to address these. When might be want an alternative to using a lambda and how can we design our APIs to be flexible in this regard. What are the principles of writing low latency code in Java? How do we tune and optimize our code for low latency? When don’t we optimize our code? Where does the JVM help and where does it get in our way? How does this apply to lambdas? How can we design our APIs to use lambdas and minimize garbage?
PackedObject is an experimental feature in IBM J9 Virtual Machine. Goal(s) of Feature: Improve serialization and I/O of Java objects Allow direct access to “native” (off-heap) data Allow for explicit source-level representation of compact data-structure Intended Use: Provide an opportunity for feedback and experimentation Not meant for production support Not a committed language change
Was jeder Java-Entwickler über Strings wissen sollteberndmueller
Strings sind wahrscheinlich der am meisten verwendete Datentyp in jeder
Java-Anwendung. Es ist daher nicht überraschend, dass JDK-Ingenieure
versuchen, Strings möglichst gut zu optimieren oder Bücher über
Performanz-Tuning und Testen dem Thema Strings ganze Kapitel widmen.
Jeder Entwickler sollte daher wissen, was Strings sind und wie sie
sinnvoll und effizient eingesetzt werden können.
Dieser Vortrag stellt JDK-Klassen vor, die mit und auf Strings
arbeiten, sowohl auf der API- aber auch auf der
Implementierungsebene. Wir beleuchten internte Strings und die für sie
verwendeten Speicherbereiche, sowie die noch recht unbekannte
"String-Deduplication"-Option des G1-Garbage-Collectors.
Mit Java 9 ändert sich die interne Repräsentation von Strings.
Wir skizzieren diese Änderungen, die nach außen unsichtbar
bleiben.
What are the Cool Kids Doing With Continuous Delivery?CA Technologies
Building a solid application delivery tool chain is no easy task. The popularity of infrastructure configuration management tools like Puppet, Chef, Salt and others are a direct result of the explosion of virtual machines needing to be maintained, configured and provisioned. Learn how you can leverage these trends and combine infrastructure configuration and release automation to build an enterprise class continuous delivery solution for your business.
For more information on DevOps solutions from CA Technologies, please visit: http://bit.ly/1wbjjqX
Pitfalls of migrating projects to JDK 9Pavel Bucek
Java 9 brings revolutionary changes. There is a big difference between their adoption and adoption of similarly revolutionary features of Java 8: lambdas and streams could gradually be included in a project, but Jigsaw requires some significant changes to the existing code. Jersey and Tyrus are popular open source libraries of considerable size and cherish backward compatibility. This session presents lessons learned during a migration to Java 9 and adoption of Jigsaw features. The nature of the projects and their features—such as resource injection or scanning and using user-provided (thus unknown, in standard dependency view) classes—make the migration particularly interesting and informative for future Java 9 adopters.
This document discusses various approaches to accessing the sun.misc.Unsafe class from outside of the JDK/JRE, as it is an internal class not intended for public use. It presents several options for retrieving an Unsafe instance, such as directly calling Unsafe.getUnsafe() (which only works inside JDK/JRE), accessing the "theUnsafe" field via reflection, or constructing a new Unsafe instance using a private constructor. However, it notes that none of these options feel quite right as sun.misc.Unsafe is an internal class, and its use is discouraged outside of the JDK/JRE.
Technische Schulden in Architekturen erkennen und beseitigenCarola Lilienthal
Beim Entwurf der Softwarearchitektur zu Beginn eines Projekts bringen die Architekten i.d.R. all ihre Erfahrung und ihr Knowhow ein und stellen eine Architektur-Blaupause für die Entwicklung bereit. Aber während der Implementierung weichen die Entwickler ungewollt mehr und mehr von diesen Vorgaben ab: Einerseits macht der Projektdruck Abweichungen notwendig, andererseits entstehen die Abweichungen ungewollt und unbemerkt. Die Architektur des Systems erodiert und es werden Schritt für Schritt technische Schulden aufgebaut. Wartung und Erweiterung der Software werden immer teurer bis zu dem Punkt, an dem jede Änderung zu einer schmerzhaften Anstrengung wird.
In diesem Vortrag berichte ich von meinen Erfahrungen der letzten zehn Jahre mit der Analyse von Softwarearchitekturen in Java (60 Systeme), C# (10 Systeme), C++(6 Systeme): Die Zuhörer wissen nach meinem Vortrag, welche Fehler sie in ihren Softwareprojekten bei der Umsetzung der Architektur nicht machen sollten, welche Prinzipien Sie einhalten sollen, um technische Schulden nicht entstehen zu lassen, welche Tools helfen, technische Schulden aufzuspüren, und wie technische Schulden abgebaut werden können.
A presentation on how automatic memory management and adaptive compilation impact on latency of applications. Includes some ideas on how to minimise these affects.
The document provides an introduction to the LMAX Disruptor, a data structure for high performance inter-thread messaging. It describes the Disruptor as allowing very fast message passing without contention by using a lock-free data structure called a ring buffer. The workshop covers the basic components of the Disruptor including the publisher, event handlers, and batch processing. It includes exercises to demonstrate wiring up a simple Disruptor configuration, adding parallel event handlers, and managing dependencies between handlers. Real-world uses like high throughput financial applications are also discussed.
Sascha Möllering discusses infrastructure as code and provides an overview of VMware SDKs, Chef, and using Chef to configure JBoss middleware. He explains that VMware has multiple SDKs and that the VI Java SDK simplifies development. Chef is introduced as a tool to automate and standardize server configurations. The presentation then covers using Chef recipes to deploy and configure JBoss application servers and integrating with JBoss Operations Network for monitoring.
The document discusses the Disruptor, a data structure and work flow that allows for high-performance concurrent programming with no contention. The Disruptor uses a ring buffer to pass messages between threads very quickly in a parallel manner. Publishers can insert events into the ring buffer, while batch event processors can read the events in batches to process them in parallel threads. The Disruptor framework encourages modeling the problem domain and provides reliable ordering, parallelism, and high performance.
Sascha Möllering discusses how his company moved from manual server setup and deployment to automated deployments using infrastructure as code and continuous delivery. They now deploy whenever needed using tools like Chef and JBoss to configure servers. Previously they faced challenges like manual processes, difficult rollbacks, and biweekly deployment windows. Now deployments are automated, safer, and can happen continuously.
All new features, expected features and speculations regarding the upcoming Java 9 release: the Jigsaw project, performance improvements and long awaited APIs:
www.takipiblog.com/java-9-the-ultimate-feature-list/
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
Java is an object-oriented programming language used widely for both desktop and mobile applications. It is portable, platform-independent, robust, and interpreted. The document lists 10 common Java interview questions and provides detailed answers on topics like Java features, objects, classes, JDK vs JRE vs JVM, StringBuffer vs StringBuilder, loops, and the final keyword. Key Java concepts covered include object-oriented programming, memory management, garbage collection, and polymorphism.
Unit No 4 Exception Handling and Multithreading.pptxDrYogeshDeshmukh1
The document discusses object oriented programming with Java and covers several topics including exception handling, multithreading, and inter-thread communication. It defines exceptions as abnormal conditions that disrupt normal program flow and explains how exception handling allows the program to continue executing. It also describes the different types of exceptions in Java and how to create and manage threads using the Thread class and Runnable interface. Key threading concepts like thread states, synchronization, and inter-thread communication techniques like wait(), notify(), and notifyAll() are explained.
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
The document discusses differences between abstract classes and interfaces in Java. It provides 7 key differences: 1) Abstract classes can have executable and unimplemented methods while interfaces only contain method signatures. 2) A class can implement multiple interfaces but extend only one abstract class. 3) Abstract classes can have non-abstract methods and variables while interfaces cannot. 4) Abstract classes can define constructors while interfaces cannot. 5) Abstract classes can have any visibility modifier while interfaces must be public or package-private. 6) Abstract classes inherit from Object while interfaces do not.
20 most important java programming interview questionsGradeup
The document discusses 20 important Java programming interview questions. It covers topics such as the differences between interfaces and abstract classes, when to use abstract classes versus interfaces, what the Serializable interface does, how to force garbage collection, the differences between StringBuffer and StringBuilder, checked and unchecked exceptions, how Java allocates stack and heap memory, Java reflection, the Java Virtual Machine, the differences between JDK and JRE, and more.
String is immutable in Java for security and efficiency reasons. Immutability allows strings to be shared and cached without risk of unexpected changes from another thread. The String class is declared final to prevent extension and mutation. Immutable strings enable safe sharing across threads and applications like databases and networking without the risk of data corruption from concurrent modifications.
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
This document provides an overview of object-oriented programming concepts in Java including encapsulation, inheritance, polymorphism, and abstraction. It also discusses key Java features like classes, interfaces, access modifiers, and differences between abstract classes and interfaces. Object-oriented principles like encapsulation, inheritance and polymorphism are explained along with examples. Common questions about Java concepts are also addressed at the end.
The document discusses key concepts related to threads and concurrency in Java. It defines processes, threads, and the Java memory model. It then covers various concurrency utilities in Java like synchronized blocks, volatile fields, atomic classes, thread pools, blocking queues, and locking mechanisms like ReentrantLock. The last part discusses high-level concurrency constructs like semaphores, latches, barriers, and phaser.
A handy notes for Java, which will help in daily programming, development and also when you are giving or taking interview; quick reference guide for daily programming & development. This book is designed to help Java developers from beginner to intermediate. Please comment your feedback.
This document provides an overview of key Java concepts including data types, OOP concepts like inheritance and polymorphism, exception handling, collections, multithreading, design patterns, and Java 8 features. It defines Java as an object-oriented programming language and describes primitive and non-primitive data types. It also summarizes access modifiers, exception types, the difference between throw and throws, and the life cycle and states of threads.
Synchronization in Java controls access to shared resources by multiple threads so that only one thread can access a resource at a time. The JVM interprets bytecode, making Java platform independent. Interfaces define methods for classes to implement, while abstract classes can include implementations along with abstract methods. Autoboxing converts primitives to wrapper types for object-oriented operations, while unboxing converts wrappers back to primitives.
Threads allow concurrent execution of code by sharing memory within a process. Globals and static variables must be synchronized to be safely accessed by multiple threads, but local variables are private to each thread. The Java Virtual Machine originally used "green threads" but now uses native operating system threads, allowing parallel execution on multi-core systems. The J2EE standard recommends avoiding synchronization and instead storing data in databases protected by transactions. Synchronization, if used, should change minimal shared state to avoid problems like deadlocks.
This document discusses Java concurrency and the Java memory model. It begins with an agenda that covers the Java memory model, thread confinement, the Java atomic API, immutable objects, and memory consumption. It then goes into more detail on the Java memory model, discussing topics like ordering, visibility, and atomicity. It provides examples and references to help understand concepts like sequential consistency and data races. It also covers thread confinement techniques like ad hoc confinement, stack confinement, and using ThreadLocal.
This document provides summaries of common Java interview questions. It discusses the differences between abstract classes and interfaces, checked and unchecked exceptions, user-defined exceptions, differences between C++ and Java, Java statements, JAR files, JNI, serialization, null interfaces, synchronized methods, singleton classes, compilation units, resource bundles, transient variables, the Collection API, iterators, observers and observables, synchronization, locks on classes, thread states, anonymous classes, primitive data types and their ranges.
This document provides an overview of the Java Virtual Machine (JVM). It discusses that the JVM is an abstract machine that implements an intermediate language between Java code and hardware. The JVM architecture includes class files, data types, memory areas like stacks and heap, and JVM instructions. Class files define the class file format that all JVM implementations must support. The JVM is a stack-based machine where frames are used to store arguments, local variables, and intermediate results.
Multithreading and concurrency in androidRakesh Jha
Here you will learn -
What is Multithreading
What is concurrency
Process Vs Thread
Improvements and issues with concurrency
Limits of concurrency gains
Concurrency issues
Threads pools with the Executor Framework
AsyncTask and the UI Thread
Code
Java concurrency allows applications to make use of multiple processors and handle asynchronous operations through the use of threads. While concurrency provides benefits like improved performance, it also introduces risks like race conditions and deadlocks if threads access shared resources unsafely. The Java threading APIs provide tools for safely managing concurrent operations through mechanisms like synchronization, locks, and concurrent collections.
The document discusses various Java concepts including object-oriented principles, inheritance, polymorphism, encapsulation, constructors, methods, exceptions, threads, and memory management. It provides definitions and explanations of key terms like inheritance, polymorphism, method overloading, overriding, checked and unchecked exceptions, static and non-static methods, and the differences between concepts like ArrayList and Vector, and method overloading versus overriding.
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025BookNet Canada
Book industry standards are evolving rapidly. In the first part of this session, we’ll share an overview of key developments from 2024 and the early months of 2025. Then, BookNet’s resident standards expert, Tom Richardson, and CEO, Lauren Stewart, have a forward-looking conversation about what’s next.
Link to recording, transcript, and accompanying resource: https://bnctechforum.ca/sessions/standardsgoals-for-2025-standards-certification-roundup/
Presented by BookNet Canada on May 6, 2025 with support from the Department of Canadian Heritage.
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveScyllaDB
Want to learn practical tips for designing systems that can scale efficiently without compromising speed?
Join us for a workshop where we’ll address these challenges head-on and explore how to architect low-latency systems using Rust. During this free interactive workshop oriented for developers, engineers, and architects, we’ll cover how Rust’s unique language features and the Tokio async runtime enable high-performance application development.
As you explore key principles of designing low-latency systems with Rust, you will learn how to:
- Create and compile a real-world app with Rust
- Connect the application to ScyllaDB (NoSQL data store)
- Negotiate tradeoffs related to data modeling and querying
- Manage and monitor the database for consistently low latencies
AI and Data Privacy in 2025: Global TrendsInData Labs
In this infographic, we explore how businesses can implement effective governance frameworks to address AI data privacy. Understanding it is crucial for developing effective strategies that ensure compliance, safeguard customer trust, and leverage AI responsibly. Equip yourself with insights that can drive informed decision-making and position your organization for success in the future of data privacy.
This infographic contains:
-AI and data privacy: Key findings
-Statistics on AI data privacy in the today’s world
-Tips on how to overcome data privacy challenges
-Benefits of AI data security investments.
Keep up-to-date on how AI is reshaping privacy standards and what this entails for both individuals and organizations.
TrsLabs - Fintech Product & Business ConsultingTrs Labs
Hybrid Growth Mandate Model with TrsLabs
Strategic Investments, Inorganic Growth, Business Model Pivoting are critical activities that business don't do/change everyday. In cases like this, it may benefit your business to choose a temporary external consultant.
An unbiased plan driven by clearcut deliverables, market dynamics and without the influence of your internal office equations empower business leaders to make right choices.
Getting things done within a budget within a timeframe is key to Growing Business - No matter whether you are a start-up or a big company
Talk to us & Unlock the competitive advantage
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...SOFTTECHHUB
I started my online journey with several hosting services before stumbling upon Ai EngineHost. At first, the idea of paying one fee and getting lifetime access seemed too good to pass up. The platform is built on reliable US-based servers, ensuring your projects run at high speeds and remain safe. Let me take you step by step through its benefits and features as I explain why this hosting solution is a perfect fit for digital entrepreneurs.
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfAbi john
Analyze the growth of meme coins from mere online jokes to potential assets in the digital economy. Explore the community, culture, and utility as they elevate themselves to a new era in cryptocurrency.
Quantum Computing Quick Research Guide by Arthur MorganArthur Morgan
This is a Quick Research Guide (QRG).
QRGs include the following:
- A brief, high-level overview of the QRG topic.
- A milestone timeline for the QRG topic.
- Links to various free online resource materials to provide a deeper dive into the QRG topic.
- Conclusion and a recommendation for at least two books available in the SJPL system on the QRG topic.
QRGs planned for the series:
- Artificial Intelligence QRG
- Quantum Computing QRG
- Big Data Analytics QRG
- Spacecraft Guidance, Navigation & Control QRG (coming 2026)
- UK Home Computing & The Birth of ARM QRG (coming 2027)
Any questions or comments?
- Please contact Arthur Morgan at [email protected].
100% human made.
Role of Data Annotation Services in AI-Powered ManufacturingAndrew Leo
From predictive maintenance to robotic automation, AI is driving the future of manufacturing. But without high-quality annotated data, even the smartest models fall short.
Discover how data annotation services are powering accuracy, safety, and efficiency in AI-driven manufacturing systems.
Precision in data labeling = Precision on the production floor.
Dev Dives: Automate and orchestrate your processes with UiPath MaestroUiPathCommunity
This session is designed to equip developers with the skills needed to build mission-critical, end-to-end processes that seamlessly orchestrate agents, people, and robots.
📕 Here's what you can expect:
- Modeling: Build end-to-end processes using BPMN.
- Implementing: Integrate agentic tasks, RPA, APIs, and advanced decisioning into processes.
- Operating: Control process instances with rewind, replay, pause, and stop functions.
- Monitoring: Use dashboards and embedded analytics for real-time insights into process instances.
This webinar is a must-attend for developers looking to enhance their agentic automation skills and orchestrate robust, mission-critical processes.
👨🏫 Speaker:
Andrei Vintila, Principal Product Manager @UiPath
This session streamed live on April 29, 2025, 16:00 CET.
Check out all our upcoming Dev Dives sessions at https://community.uipath.com/dev-dives-automation-developer-2025/.
Technology Trends in 2025: AI and Big Data AnalyticsInData Labs
At InData Labs, we have been keeping an ear to the ground, looking out for AI-enabled digital transformation trends coming our way in 2025. Our report will provide a look into the technology landscape of the future, including:
-Artificial Intelligence Market Overview
-Strategies for AI Adoption in 2025
-Anticipated drivers of AI adoption and transformative technologies
-Benefits of AI and Big data for your business
-Tips on how to prepare your business for innovation
-AI and data privacy: Strategies for securing data privacy in AI models, etc.
Download your free copy nowand implement the key findings to improve your business.
Artificial Intelligence is providing benefits in many areas of work within the heritage sector, from image analysis, to ideas generation, and new research tools. However, it is more critical than ever for people, with analogue intelligence, to ensure the integrity and ethical use of AI. Including real people can improve the use of AI by identifying potential biases, cross-checking results, refining workflows, and providing contextual relevance to AI-driven results.
News about the impact of AI often paints a rosy picture. In practice, there are many potential pitfalls. This presentation discusses these issues and looks at the role of analogue intelligence and analogue interfaces in providing the best results to our audiences. How do we deal with factually incorrect results? How do we get content generated that better reflects the diversity of our communities? What roles are there for physical, in-person experiences in the digital world?
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...Alan Dix
Talk at the final event of Data Fusion Dynamics: A Collaborative UK-Saudi Initiative in Cybersecurity and Artificial Intelligence funded by the British Council UK-Saudi Challenge Fund 2024, Cardiff Metropolitan University, 29th April 2025
https://alandix.com/academic/talks/CMet2025-AI-Changes-Everything/
Is AI just another technology, or does it fundamentally change the way we live and think?
Every technology has a direct impact with micro-ethical consequences, some good, some bad. However more profound are the ways in which some technologies reshape the very fabric of society with macro-ethical impacts. The invention of the stirrup revolutionised mounted combat, but as a side effect gave rise to the feudal system, which still shapes politics today. The internal combustion engine offers personal freedom and creates pollution, but has also transformed the nature of urban planning and international trade. When we look at AI the micro-ethical issues, such as bias, are most obvious, but the macro-ethical challenges may be greater.
At a micro-ethical level AI has the potential to deepen social, ethnic and gender bias, issues I have warned about since the early 1990s! It is also being used increasingly on the battlefield. However, it also offers amazing opportunities in health and educations, as the recent Nobel prizes for the developers of AlphaFold illustrate. More radically, the need to encode ethics acts as a mirror to surface essential ethical problems and conflicts.
At the macro-ethical level, by the early 2000s digital technology had already begun to undermine sovereignty (e.g. gambling), market economics (through network effects and emergent monopolies), and the very meaning of money. Modern AI is the child of big data, big computation and ultimately big business, intensifying the inherent tendency of digital technology to concentrate power. AI is already unravelling the fundamentals of the social, political and economic world around us, but this is a world that needs radical reimagining to overcome the global environmental and human challenges that confront us. Our challenge is whether to let the threads fall as they may, or to use them to weave a better future.
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...Alan Dix
Java Concurrency Quick Guide
1. Java Concurrency
lecture notes
Anton Shchastnyi
11/24/2011
A brief overview of the Java Concurrency. Main definitions, liveness issues, high level concurrency objects of
the Java Platform, Standard Edition.
2. Java Concurrency - Lecture Notes |2
Table of Contents
Contents
Table of Contents ..................................................................................................................................................... 2
Concurrency Definitions ........................................................................................................................................... 3
Process VS Thread ................................................................................................................................................ 3
Concurrency in Java .............................................................................................................................................. 3
The Java Memory Model ...................................................................................................................................... 3
Atomic Operation ................................................................................................................................................. 3
Volatile.................................................................................................................................................................. 3
Nonblocking Algorithms ....................................................................................................................................... 4
Liveness Issues .......................................................................................................................................................... 5
Deadlock ............................................................................................................................................................... 5
Livelock ................................................................................................................................................................. 5
Starvation ............................................................................................................................................................. 5
Guarded Blocks ..................................................................................................................................................... 5
Immutable Objects ............................................................................................................................................... 5
High Level Concurrency Objects ............................................................................................................................... 6
Locks ..................................................................................................................................................................... 6
Executors .............................................................................................................................................................. 7
Futures and Callables ........................................................................................................................................... 8
java.lang.Thread VS the Executor Framework ..................................................................................................... 8
Thread Pools ......................................................................................................................................................... 8
Fork/Join in Java 7 ................................................................................................................................................ 9
Concurrent Collections ....................................................................................................................................... 10
References .............................................................................................................................................................. 11
About the Author ................................................................................................................................................... 12
3. Java Concurrency - Lecture Notes |3
Concurrency Definitions
Concurrency is the ability to run several parts of a program in parallel.
Concurrency can highly improve the speed of a program if certain tasks could be performed asynchronously or in
parallel.
Process VS Thread
Process: A process runs independently and isolated of other processes. It cannot directly access shared data
in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and
CPU time.
Thread: Threads are so called lightweight processes which have their own call stack but can access shared
data. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own
memory cache. A thread can re-read the shared data, when this happens in Java will be explained in Java
memory model part of this article.
Concurrency in Java
A Java application runs in its own process.
Within a Java application you work with several threads to achieve parallel processing or asynchronously behavior.
Java supports threads as part of the Java language. Java 1.5 also provides improved support for concurrency with the
in the package java.util.concurrent.
Java also provides locks to protect certain parts of the coding to be executed by several threads at the same time.
The simplest way of locking a certain method or Java class is to use the keyword "synchronized" in a method
declaration.
The Java Memory Model
The Java memory model describes
the communication between the memory of the threads and the main memory
which operations are atomic
the ordering of the operations.
Atomic Operation
An atomic operation is an operation which is performed as a single unit of work without the possibility of
interference from other operations.
In Java the language specification guarantees that that reading or writing a variable is atomic (unless the variable is
of type long or double). Long and double are only atomic if they declared as volatile.
Volatile
The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and
that reads of the field should always read from memory.
If a variable is declared as volatile then is guaranteed that any thread which reads the field will see the most recently
written value.
This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without
using native or standard library-based synchronization.
(This does not apply to long or double fields, which may be non-atomic on some JVMs. However, it always applies to
reference-typed fields.)
The operation i++ is not atomic in Java for the primitives.
It first reads the value which is currently stored in i (atomic operations).
Then it increments it (atomic operation). But between the read and the write the value of i might have changed.
4. Java Concurrency - Lecture Notes |4
Since Java 1.5 the java language provides atomic variables
AtomicInteger, AtomicLong atomic methods:
getAndDecrement(),
getAndIncrement()
getAndSet()
BigDecimal is only about to be more precise than Float or Double
Nonblocking Algorithms
Java 5.0 provides supports for additional atomic operations. This allows to develop algorithm which are
non-blocking algorithm, e.g. which do not require synchronization, but are based on low-level atomic hardware
primitives such as compare-and-swap (CAS).
A CAS operation checks if the variable has a certain value and if it has this value it will perform this operation.
Non-blocking algorithm are usually much faster than blocking algorithms as the synchronization of threads appears
on a much lower level (hardware).
The JDK itself extensively uses non-blocking algorithms to increase the platform performance. Developing correct
non-blocking algorithm is not a trivial task.
5. Java Concurrency - Lecture Notes |5
Liveness Issues
Deadlock
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Livelock
A thread often acts in response to the action of another thread. If the other thread's action is also a response to the
action of another thread, then livelock may result.
As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked —
they are simply too busy responding to each other to resume work.
This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston
pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone
moves to his right, while Gaston moves to his left. They're still blocking each other, so...
Starvation
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to
make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads.
For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread
invokes this method frequently, other threads that also need frequent synchronized access to the same object will
often be blocked.
Guarded Blocks
Threads often have to coordinate their actions. The most common coordination idiom is the guarded block.
Such a block begins by polling a condition that must be true before the block can proceed.
Immutable Objects
An object is considered immutable if its state cannot change after it is constructed.
Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.
Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be
corrupted by thread interference or observed in an inconsistent state.
6. Java Concurrency - Lecture Notes |6
High Level Concurrency Objects
Synchronized blocs and monitors with java.lang.Thread class are adequate for very basic tasks,
but higher-level building blocks are needed for more advanced tasks.
This is especially true for massively concurrent applications that fully exploit today's multiprocessor and multi-core
systems.
In this section we'll look at some of the high-level concurrency features introduced with Java 5.0.
Most of these features are implemented in the new java.util.concurrent packages. There are also new concurrent
data structures in the Java Collections Framework.
Lock objects Support locking idioms that simplify many concurrent applications.
Executors Define a high-level API for launching and managing threads.
Executor implementations provided by java.util.concurrent provide thread pool
management suitable for large-scale applications.
Concurrent collections Make it easier to manage large collections of data, and can greatly reduce the need
for synchronization.
Atomic variables Have features that minimize synchronization and help avoid memory consistency
errors.
ThreadLocalRandom Provides efficient generation of pseudorandom numbers from multiple threads
(in JDK 7).
Locks
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods
and statements.
Locks allow more flexible structuring, may have quite different properties, and may support multiple associated
Condition objects.
With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the
automatic release of locks that occurs with synchronized methods and statements. In most cases, the following
idiom should be used:
Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}
Lock implementations provide additional functionality over the use of synchronized methods and statements.
A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock,
such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such
specialized semantics then the implementation must document those semantics.
7. Java Concurrency - Lecture Notes |7
java.util.concurrent.locks
Interface Lock
Method Summary
void lock()
Acquires the lock (similar to entering the synchronized section).
void lockInterruptibly()
Acquires the lock unless the current thread is interrupted.
Condition newCondition()
Returns a new Condition instance that is bound to this Lock instance.
boolean tryLock()
Acquires the lock only if it is free at the time of invocation.
boolean tryLock(long time, TimeUnit unit)
Acquires the lock if it is free within the given waiting time and the current thread has not been
interrupted.
void unlock()
Releases the lock.
All Known Implementing Classes
ReentrantLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
Executors
In large-scale applications, it makes sense to separate thread management and creation from the rest of the
application. Objects that encapsulate these functions are known as executors.
Executors Types
Executor Interfaces Executor A simple interface that supports launching new tasks.
(new Thread(r)).start(); → e.execute(r);
ExecutorService A subinterface of Executor, which adds features that help
manage the lifecycle, both of the individual tasks and of the
executor itself.
execute() accepts Runnable;
submit() accepts Runnable and Callable.
Returns a Future object, which is used to
retrieve the Callable return value and to
manage the status of both Callable and
Runnable tasks.
Provides methods for submitting large collections of
Callable objects.
Provides a number of methods for managing the shutdown
of the executor. To support immediate
shutdown, tasks should handle interrupts
correctly.
ScheduledExecutorService A subinterface of ExecutorService, supports future and/or
periodic execution of tasks.
The ScheduledExecutorService interface supplements the
methods of its parent ExecutorService with schedule, which
executes a Runnable or Callable task after a specified delay. In
8. Java Concurrency - Lecture Notes |8
addition, the interface defines scheduleAtFixedRate and
scheduleWithFixedDelay, which executes specified tasks
repeatedly, at defined intervals.
Thread Pools The most common kind of executor implementation.
Fork/Join A framework (new in JDK 7) for taking advantage of multiple
processors.
Futures and Callables
Callable<V> A task that returns a result and may throw an exception.
method: Implementors define a single method with no arguments
V call() throws Exception called call().
Computes a result, or throws an exception if unable to do so. The Callable interface is similar to Runnable, in that both
are designed for classes whose instances are potentially
executed by another thread. A Runnable, however, does
not return a result and cannot throw a checked
exception.
The Executors class contains utility methods to convert
from other common forms to Callable classes.
java.lang.Thread VS the Executor Framework
Using Threads directly has the following disadvantages:
Creating a new thread causes some performance overhead
Too many threads can lead to reduced performance, as the CPU needs to switch between these threads
You cannot easily control the number of threads, therefore you may run into out of memory errors due to
too many threads
The java.util.concurrent package offers improved support for concurrency compared to threads.
java.lang.Thread Threads pools
with the Executor Framework
new Thread(new( RunnableTask() ).start() Executor executor = anExecutor;
for each of a set of tasks executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
Thread pool manages a pool of worker threads. The thread pool contains a work queue which holds tasks waiting to
get executed.
The Executor framework provides example implementation of the java.util.concurrent.Executor.
The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for
termination.
Thread Pools
Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of
memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant
memory management overhead.
One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads
running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread.
Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks
than threads.
9. Java Concurrency - Lecture Notes |9
Executor An object that executes submitted Runnable tasks
ExecutorService An Executor that provides methods to manage termination and
methods that can produce a Future for tracking progress of one or more
asynchronous tasks.
All Known Implementing Classes:
AbstractExecutorService,
ScheduledThreadPoolExecutor,
ThreadPoolExecutor
The ThreadPoolExecutor class provides an extensible thread pool implementation.
The Executors class provides convenient factory methods for these Executors.
An important advantage of the fixed thread pool is that applications using it degrade gracefully.
To understand this, consider a web server application where each HTTP request is handled by a separate thread. If
the application simply creates a new thread for every new HTTP request, and the system receives more requests
than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of
all those threads exceed the capacity of the system.
With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as
quickly as they come in, but it will be servicing them as quickly as the system can sustain.
java.util.concurrent.Executors class Methods to create an executors that use threas pools
newFixedThreadPool() Creates an executor with a fixed thread pool.
newCachedThreadPool() Creates an executor with an expandable thread pool.
This executor is suitable for applications that launch many short-lived
tasks.
newSingleThreadExecutor() Creates an executor that executes a single task at a time.
If none of the executors provided by the above factory methods meet your needs, constructing instances of
java.util.concurrent.ThreadPoolExecutor or java.util.concurrent.ScheduledThreadPoolExecutor will give you
additional options.
Fork/Join in Java 7
New in the Java SE 7 release, the fork/join framework is an implementation of the ExecutorService interface that
helps you take advantage of multiple processors.
The fork/join framework allows you to distribute a certain task on several workers and then wait for the result.
It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available
processing power to make your application wicked fast.
For Java 6 you have to add this framework manually (jsr166.jar from http://g.oswego.edu/dl/concurrency-
interest/).
10. J a v a C o n c u r r e n c y - L e c t u r e N o t e s | 10
Concurrent Collections
The java.util.concurrent package includes a number of additions to the Java Collections Framework. These are most
easily categorized by the collection interfaces provided.
BlockingQueue Defines a FIFO data structure that blocks or times out
when you attempt to add to a full queue, or retrieve from
an empty queue.
ConcurrentMap The interface defines useful atomic operations.
These operations remove or replace a key-value pair
only if the key is present, or add a key-value pair only if
the key is absent.
Making these operations atomic helps avoid
synchronization.
ConcurrentNavigableMap This interface supports approximate matches.
java.util.Map
ConcurrentMap
ConcurrentNavigableMap
A concurrent analog of ConcurrentHashMap ConcurrentSkipListMap A concurrent analog of
HashMap TreeMap
11. J a v a C o n c u r r e n c y - L e c t u r e N o t e s | 11
References
[1] Lars Vogel, Java Concurrency / Multithreading – Tutorial,
http://www.vogella.de/articles/JavaConcurrency/article.html
[2] Oracle, Inc, Java Tutorials – Concurrency,
http://download.oracle.com/javase/tutorial/essential/concurrency/
[3] B. Goetz, with T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, D. Lea, Java Concurrency in Practice,
http://www.informit.com/store/product.aspx?isbn=0321349601
12. J a v a C o n c u r r e n c y - L e c t u r e N o t e s | 12
About the Author
Anton Shchastnyi is a software engineer living in Ukraine. He mainly focuses on developing web and desktop
applications on Java platform. He also enjoys writing, and does quite a bit of tutorials and learning materials on Java
and related technologies (http://antonshchastnyi.blogspot.com/, http://schaan.habrahabr.ru/blog).