The document discusses various Apache Commons utilities including configuration, lang, IO, and bean utilities. It provides examples of using the Configuration utility to load property files, the StringUtils class for string operations, ToStringBuilder for object toString methods, ArrayUtils for array operations, IOUtils for input/output streams, and making classes immutable by preventing field mutation.
어느덧 스무살이 된 자바. 좋든싫든 프로그래밍의 세계에 몸담고 있는 이상 부딪히지 않을 수 없는 언어인데요, 이 자바에 대한 올바른 모습의 이해화 앞으로 나아가야 할 방향을 모색해본다는 의미에서 "모던 자바의 역습"이라는 타이틀로 실시한 온라인 세미나의 슬라이드 자료입니다.
진행자: 김대우(http://lekdw.blogspot.kr/)
정도현(http://moreagile.net)
이번 세미나는 게임개발자이신 김대우님을 모시고 진행하게 되었는데요 자바 언어와 관련 하여 다음과 같은 주제로 두시간에 걸쳐 발표를 진행합니다.
- 간단히 살펴보는 자바20년의 발자취
- 자바를 둘러싼 진실 혹은 거짓(성능,생산성,품질)
- SI영역 이외에서 자바의 가치
- 모던자바의 역습: 자바8과 함수형 프로그래밍
- 자바 개발의 새로운 패러다임들
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
While software engineers can disagree on almost any concept of programming best-practice, the necessity of writing unit tests remains undisputed. With the advent of concurrent applications and the ongoing deprecation of the one-thread-per-request model, unit tests do however miss an increasing fraction of programming errors such as race conditions or dead-locking code. But is it even possible to write tests that revise such errors? In the end, a good unit test is characterized by a determined execution path what effectively prevents the use of concurrency within a single test. However, there are tools and programming principles that allow for unit tests of concurrent code. This talk reviews typical mistakes made when concurrent code is tested and introduces Thread Weaver, a test suite for writing valid unit tests that uncover concurrency-related programming errors.
어느덧 스무살이 된 자바. 좋든싫든 프로그래밍의 세계에 몸담고 있는 이상 부딪히지 않을 수 없는 언어인데요, 이 자바에 대한 올바른 모습의 이해화 앞으로 나아가야 할 방향을 모색해본다는 의미에서 "모던 자바의 역습"이라는 타이틀로 실시한 온라인 세미나의 슬라이드 자료입니다.
진행자: 김대우(http://lekdw.blogspot.kr/)
정도현(http://moreagile.net)
이번 세미나는 게임개발자이신 김대우님을 모시고 진행하게 되었는데요 자바 언어와 관련 하여 다음과 같은 주제로 두시간에 걸쳐 발표를 진행합니다.
- 간단히 살펴보는 자바20년의 발자취
- 자바를 둘러싼 진실 혹은 거짓(성능,생산성,품질)
- SI영역 이외에서 자바의 가치
- 모던자바의 역습: 자바8과 함수형 프로그래밍
- 자바 개발의 새로운 패러다임들
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
While software engineers can disagree on almost any concept of programming best-practice, the necessity of writing unit tests remains undisputed. With the advent of concurrent applications and the ongoing deprecation of the one-thread-per-request model, unit tests do however miss an increasing fraction of programming errors such as race conditions or dead-locking code. But is it even possible to write tests that revise such errors? In the end, a good unit test is characterized by a determined execution path what effectively prevents the use of concurrency within a single test. However, there are tools and programming principles that allow for unit tests of concurrent code. This talk reviews typical mistakes made when concurrent code is tested and introduces Thread Weaver, a test suite for writing valid unit tests that uncover concurrency-related programming errors.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
The programming world is moving towards functional programming. All the major and popular programming languages (including Java, C++, C#, Swift, and Python) support functional programming. Functional programming languages such as Clojure, Scala, and F# are on the rise. This talk introduces functional programming to those who are new to this paradigm using lambda functions in Java 8. The talk will cover syntax and semantics of lambda functions, moving from external iteration to internal iteration, and how lambda functions can result in shorter and more readable code. If you are new to functional programming and want productivity gains from using Java’s lambda functions, this talk is certainly for you.
Concurrent Programming in Java provides a brief overview of the following topics:
• Java language support for concurrency
• Concurrency utilities (java.util.concurrent package)
• Java collections for multithreading (java.util package)
• Parallel streams in Java 8.
Try out the examples. Source code here: https://github.com/CodeOpsTech/ConcurrentJava
An overview how to realize code generation of languages on the JVM that implement other class layouts than the Java programming languages. As an example, the inline-mock-maker for Mockito is discussed which supports languages like Kotlin that make any property final by default.
Let us explore Java 8 features and start using it in your day to day work. You will be surprised how Java has evolved to become so different yet easy & powerful. In this presentation, we discuss Java 8 Stream API.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
The programming world is moving towards functional programming. All the major and popular programming languages (including Java, C++, C#, Swift, and Python) support functional programming. Functional programming languages such as Clojure, Scala, and F# are on the rise. This talk introduces functional programming to those who are new to this paradigm using lambda functions in Java 8. The talk will cover syntax and semantics of lambda functions, moving from external iteration to internal iteration, and how lambda functions can result in shorter and more readable code. If you are new to functional programming and want productivity gains from using Java’s lambda functions, this talk is certainly for you.
Concurrent Programming in Java provides a brief overview of the following topics:
• Java language support for concurrency
• Concurrency utilities (java.util.concurrent package)
• Java collections for multithreading (java.util package)
• Parallel streams in Java 8.
Try out the examples. Source code here: https://github.com/CodeOpsTech/ConcurrentJava
An overview how to realize code generation of languages on the JVM that implement other class layouts than the Java programming languages. As an example, the inline-mock-maker for Mockito is discussed which supports languages like Kotlin that make any property final by default.
Let us explore Java 8 features and start using it in your day to day work. You will be surprised how Java has evolved to become so different yet easy & powerful. In this presentation, we discuss Java 8 Stream API.
Writing code that writes code - Nguyen LuongVu Huy
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
This presentation describes key concepts in Java. I call it The Java Quicky.
This is part of a series of presentations to cover the Java programming language and its new offerings and versions in depth.
This is my attempt to compose a brief and cursory introduction to concepts in Java programming language. I call it Java Quicky.
I plan to extend and enhance it over time.
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...WebStackAcademy
A collection is essentially a group of objects of a similar type. The collection framework in Java (commonly known as the Java Collection Framework) is comprised of a collection of types that enable you to implement complex data structures seamlessly. The collection interfaces in the Java Collections Framework include: Collection, List, Set, Map, and so on. And, the major classes in this framework are: ArrayList, LinkedList, HashSet, HashMap, and the like. The Java Collections Framework is contained inside the java.util.Collection package.
To iterate over a collection, we need an iterator. The java.util.Iterator package contains methods such as hasNext(), next(), and remove(). The hasNext() method returns true if there are more elements in the collection. The next() method returns the next element in the collection. The remove() method removes the last element from a collection.
Generics is a feature of the Java Language that promotes type safety, code manageability and efficiency and, most importantly, much cleaner and reduced code. You can use generics to create type safe collections with no boxing and un-boxing overhead; this is also known as parametric polymorphism.
While Google is adding Kotlin as an official Android language, we're also expanding our research on this language. It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise and makes coding a satisfying and efficient experience.
Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
Please see my presentation to learn more!
While most bugs reveal their cause within their stack trace, Java’s OutOfMemoryError is less talkative and therefore regarded as being difficult to debug by a majority of developers. With the right techniques and tools, memory leaks in Java programs can however be tackled like any other programming error. This talks discusses how a JVM stores data, categorizes different types of memory leaks that can occur in a Java program and presents techniques for fixing such errors. Furthermore, we will have a closer look at lambda expressions and their considerable potential of introducing memory leaks when they are used incautiously.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
4. APACHE COMMONS - CONFIGURATION
org.apache.commons.configuration
To load a properties file:
PropertiesConfiguration config = new
PropertiesConfiguration(“usergui.properties”);
If we do not specify an absolute path, the file will be
searched automatically in the following locations:
in the current directory
in the user home directory
in the classpath
If a property is named “include” and the value of that
property is the name of a file on the disk, that file will 4
be included into the configuration.
9. APACHE COMMONS – LANG - STRINGUTILS
org.apache.commons.lang.StringUtils
Methods:
1. isEmpty :- Checks if a String is empty (“”) or null.
2. isBlank :- Checks if a String is whitespace, empty or null.
3. isAlpha :- Checks if a String contains only alphabets
4. isNumeric :- Checks if a String contains only nuerics
5. defaultIfEmpty(String str, String defString) :- If str is
empty or null, “defString” is returned else “str” is
returned
6. reverseDelimited :-Reverses a String that is delimited by
a specific character
7. leftPad / rightPad 9
10. APACHE COMMONS – LANG – STRINGUTILS (CONT…)
String str1 = null;
boolean result = false;
result = StringUtils.isEmpty(str1); // true
str1 = "str123";
result = StringUtils.isAlphanumeric(str1); //true
result = StringUtils.isNumeric(str1); //false
str1 = "7";
str1 = StringUtils.leftPad(str1, 3, '0'); //007
str1 = "172.168.1.44";
str1 = StringUtils.reverseDelimited(str1, '.'); //44.1.168.172
10
11. APACHE COMMONS – LANG - TOSTRINGBUILDER
public class ToStringBuilderDemo {
public static void main(String args[]){
System.out.println(new Emp(7,"Java",99.99));
}
}
class Emp{
int id;
String name;
double salary;
public Emp(int id, String name, double salary){
this.id = id; this.name = name; this.salary = salary;
}
/* here comes accessors and mutators */
public String toString(){
return ToStringBuilder.reflectionToString(this);
11
}
}
OUTPUT: com.commons.examples.Emp@10b30a7[id=7,name=Java,salary=99.99]
12. APACHE COMMONS – LANG - ARRAYUTILS
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
public class ArrayUtilsDemo {
public static void main(String args[]){
String weekends[] = {"friday","saturday","sunday"};
String weekdays[] = {"monday", "tuesday", "wednesday", "thursday"};
String days[] = (String[])ArrayUtils.addAll(weekends, weekdays);
System.out.println(ArrayUtils.isEmpty(days));
System.out.println(ArrayUtils.isSameLength(weekends, weekdays));
Integer values[] = new Integer[10];
Arrays.fill(values, 1);
int intValues[] = ArrayUtils.toPrimitive(values,0);
}
}
12
13. I I I I O O O
I II
I I I O O O
I O O O
I II I I O O O O
Input Output 13
15. APACHE COMMONS – IO (CONT…)
Task of reading bytes from a URL:
TRADITIONAL
15
IOUtils
16. APACHE COMMONS – IO (CONT…)
File dir = new File(".");
String[] files = dir.list( new
PrefixFileFilter("Test") );
for ( int i = 0; i < files.length; i++ ) { 16
System.out.println(files[i]);
}
19. SEQUENTIAL WEB SERVER
class SingleThreadWebServer{
public static void main(String args[]){
ServerSocket socket = new ServerSocket(80);
while(true){
Socket connection = socket.accept();
handleRequest(connection);
}
}
}
Drawback: thread “main” is responsible for handling all
requests one after the other
19
20. WEB SERVER THAT STARTS A NEW THREAD FOR EACH REQUEST
class ThreadPerTaskWebServer{
public static void main(String args[]){
ServerSocket socket = new ServerSocket(80);
while(true){
final Socket connection = socket.accept();
Runnable r = new Runnable(){
public void run(){
handleRequest(connection);
}
};
new Thread(r).start();
}
}
}
20
Drawback: may cause “OutOfMemory” error as there is
no boundary on thread creation.
21. WEB SERVER USING A THREAD POOL
class TaskExecutionWebServer{
private static final int NTHREADS = 100;
private static final Executor exec =
Executors.newFixedThreadPool(NTHREADS);
public static void main(String args[]){
ServerSocket socket = new ServerSocket(80);
while(true){
final Socket connection = socket.accept();
Runnable task = new Runnable(){
public void run(){
handleRequest(connection);
}
};
exec.execute(task);
} 21
}
}
23. SYNCHRONIZATION
Synchronization is built around an internal entity known as the
intrinsic lock or monitor lock. Intrinsic lock play a role in both
aspects of synchronization: enforcing exclusive access to an object’s
state and establishing happens-before relationships that are
essential to visibility.
Drawbacks:
Locking
Blocking
Context Switching
Possibility of Deadlock
23
24. VOLATILE
A volatile variable is not allowed to have a local copy
of a variable that is different from the value currently
held in “main” memory.
Volatile variables cannot be used to construct
atomic compound actions(i++). This means that
volatile variables cannot be used:
when one variable depends on another
when the new value of a variable depends on its old value.
24
25. ATOMIC INTEGER
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void incrementCount() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
25
26. MUTABLE VS. IMMUTABLE
Mutable: When we have a reference to an instance of
an object, the contents of that instance can be altered.
For Ex: class
Person, Employee, java.math.BigInteger, etc.
Immutable: When you have a reference to an instance
of an object, the contents of that instance cannot be
altered.
For Ex: all wrapper classes (Integer,String,etc)
26
27. BUILDING AN IMMUTABLE CLASS
Make all fields private.
Don’t provide mutators (setter methods)
Ensure that methods can't be overridden by either
making the class final (Strong Immutability) or
making your methods final (Weak Immutability).
If a field isn't primitive or immutable, make a deep
clone on the way in and the way out.
27
28. public final class BetterPerson{
private String firstName;
private String lastName;
private Date dob;
public BetterPerson( String firstName, String lastName, Date dob){
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date( dob.getTime() ); //way in
}
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public Date getDOB(){
return new Date( this.dob.getTime() ); //way out
}
//No mutators at all i.e., setter methods
28
}