Recipe to become a millionaire in India

This is the recipe to become a millionaire by the age of 30 who are born in India.

  1. At the age of 17, join a B.tech course in computer science.
  2. Learn one programming language(Java or Python) for one year.
  3. Focus on Data structures and algorithms.
  4. Concentrate and practice competitive coding in sites like hacker rank etc for one year.
  5. Go through the interview questions in GeeksforGeeks for Google and Amazon etc.
  6. Ask for referral from the insiders of popular MAANG companies using askreferral.io
  7. By the age of 21, end of B.Tech, get placed for a package of >= 12LPA.
  8. Now you are eligible for a loan of >= 6o lakhs in Indian banks.
  9. Take the loan and buy a nice plot at the outskirts of a metropolitan city.
  10. Use most of your salary for EMIs.
  11. Get promoted after three years at the age of 24 and earn close to 24 LPA.
  12. Take loan of 60 more lakhs and buy one more plot.
  13. Work for a year(age: 25) and move to the US or Europe (should be able to save 40 lakhs a year).
  14. Get App referrals for different apps you would install in new country here
  15. Take home loan of 1.5 crores and start building apartments in your plot with a minimum of 10 flats.
  16. By the age of 30, you would have earned a salary of (12*3+24*1+70*5) = 4.1 crores.
  17. Your total loan amount is (60+60+150) = 2.7 crores.
  18. With interest and your expenses, you can safely repay your loans by the age of 30 and you will be left with 10 flats in the city.
  19. It is no longer outskirts as the city would have been expanded and developed in 10 years.
  20. Even for a flat worth of 60 lakhs, your net worth would be 6 crores with a steady cash flow of rental income of >= 1.5 lakh per month for the rest of your life.
  21. Or you can choose to only buy land and easily make your investments worth 3x times on average in 10 years. This makes your net worth close to 12 crores.
  22. A lot is dependent on the choice of location to buy the plot, interest rates and tenure of bank loan chosen, choice of the builder in case you are constructing apartments etc.

Some of the popular mistakes people do that deviate from this process.

  1. Going for higher education taking education loan.
  2. Not focusing on getting a high paying job.
  3. Getting married early and spending all the earnings for ceremonies etc.

Essence of Rich Dad Poor Dad

Identify what are assets and what are liabilities:

This is the first and fundamental lesson to be learned by anybody starting their financial career. Anything that brings money to your income statement is your asset. Lesser the need for your presence to make that asset work better. otherwise, it will not be an easily scalable model.

Some of the businesses of that kind are:

  1. Rental income from a busy and prominent area of a city. This income keeps growing with time along with inflation. Apart from this cash flow, the land value will grow which makes your net worth grow. But the initial investment is usually high which makes it hard for common people to buy and hence a high moat business. If you have enough money, you can start buying and earn. otherwise, you need to envision the area which is going to grow huge next in the city, buy there and wait for a few years.
  2. Create a web/internet/app footprint that has a high traffic rate. This could potentially create ad revenue.

Increase the asset column.

Don’t work for money, make money work for you.

Rich buy luxuries late:

  1. Home loan, car loan, maintenance, luxury marriages, vacations and parties.

Poor guys income statement compared to rich guys income statement:

rdpd.jpg

How corporations help rich with taxes:

Rich people show their income as the corporation’s income and subtract expenses of the corporation from the income to get taxable income. This saves a lot of tax amount, unlike the salaried employee.

5oxAy.png

Corporations earn, spend and then pay taxes on the rest.

Individuals earn, get taxed and then spend.

Listing some assets:

  1. Businesses that do not require my presence.
  2. Stocks – Fortunes are made in new stock issues(new stocks are tax-free).
  3. Bonds.
  4. Income generating real estate.
  5. Notes (IOUs).
  6. Royalties from intellectual property.

Dimensions of financial literacy:

  1. Accounting:
  2. Investing:
  3. Understanding markets:
  4. The law:

Markov Decision processes

Markov decision process.PNG

A tuple – (S,s1,A,P,R)

S – finite set of states.

s1 – initial state.

A – finite set of actions.

P – Given a state s1 and action a, what is the probability of ending up at a particular state s2? This information is provided by P. This is called a State transition probability matrix. S*A*S

R – What is the reward for taking an action a at the state s?

Pi – Policy, what action to take at which state? A mapping from state space to action space. The optimal policy is the policy with the maximum reward.

Value function – Expected reward starting from state s and following policy pi.

Bellman equations –

Bellman

Bellman equation.PNG

Ways to find an optimal policy:

Optimal policy when starting in state s is the policy whose value function is maximum starting from state s.

Think about the case where a particular policy is always better than another policy for all initial states. The first policy is greater than second policy and this is called partial ordering.

Theorem:

There always exists a policy such that the partial ordering of it with all other policies is greater or equal. Such a policy/policies is called optimal policy.

Iterative methods:

  1. Policy iteration:
    1. At each state, pick the action with max value function.
    2. you get the new policy.
    3. Again go to step 1 and loop until the new policy and old policy are same.
  2. Value iteration:
    1. Finding an optimal value function rather than explicit policy.
    2. For every iteration improve value vector.
    3. once you converge to a particular value vector, use it to find the optimal policy.
    4. Value iteration.PNG
    5. This is cheap compared to policy iteration.

Model-free methods:

Reinforcement learning is Markov decision process with unknown transition model and/or reward distribution.

Agent can observe samples and induce transition model and reward distribution from that.

Q-learning:

Uses Q-values instead of the value function.

To be continued……….

q-learning


Utility: Utility of the policy at a state is what happens if we start running from that state.

Reward gives us immediate feedback but utility gives us long-term feedback. utilities allow you to take short-term negatives for long-term positives.


Credit assignment problem:


 

Decision trees

What are decision trees?

Decision trees are classification models built using a tree where a particular feature is selected for branching at different levels down the tree.

They help you to create non-linear boundaries with series of linear questions.

Decision tree

The primary choice to make is which feature to use for splitting first?

The objective in choosing the order of split is to further narrow down the possibilities faster. For example, Animal? Person? famous? living? singer? female? Michael jackson?

If you have started with Michael, if I said yes, then that’s good, but if I said no, you effectively narrowed down almost nothing.

We use info gain or Gini to make that decision.

Info gain:

infogain

but what does the info gain represent?

Info gain of a particular feature(work experience in above example) represents the predictability gain as we go down one level using that feature.

So, How is this predictability gain calculated?

This is measured by difference in predictability at parent node and expected sum of predictabilities in child nodes.

What is predictability at a node?

If number of positive and negative examples at a particular node is almost equal, then it is equally likely for a new example at that node to be either positive or negative.

If number of positive examples is far more than the number of negative examples at a particular node, then we can say with much more confidence that a new example at this node is more likely to be positive.

Second case is more predictable and contains less surprise, whereas first case is less predictable and has more surprise.

Now we use Entropy to quantify surprise at any node. How?

entropy

If all the samples belong to the same class, entropy is 0. If the samples are evenly distributed among all classes, then the entropy is 1.

  1. How to train?
    1. How to select the next best feature for branching?
      1. Calculate info-gain for all the features and select the one with maximum.
  2. How to predict?
    1. Just pass the test example down the tree and you have your classification at the leaf node.
  3. How to write a decision tree in python using scikit?
    1. writing the classifierdtclf
    2. visualizing the decision treevizdt

When to use decision trees?

  1. well-suited for categorical data.

How much training data do you need?

Nature of decision boundary

Decision trees are interpretable, unlike neural networks. Here you can exactly understand why a classifier makes a decision.

They are weak learners and hence good for ensemble methods.

They can handle unbalanced data sets, 1 % positive examples and 99 % negative examples.

This is Univariate – does not combine features.


Expressiveness among all possible decision trees in n-attributes:


How to deal with continuous attributes? Age,weight,distance

It does make sense to repeat an attribute along a path of a tree if attributes are discrete. If attributes are continuous, then you ask different questions for same attributes.


What to do to avoid overfitting in decision tree?

  1. like usually, using cross validation.
  2. Checking with cross validation at every time you expand the tree and the cv score is less than a particular threshold, then stop the expansion.
  3. Or first, expand the whole tree and start pruning back the leaves and check cv score at each step.

Algorithms:

ID3: Top down


Tuning parameters in sklearn:

  1. min_samples_split(default=2):  If node contains only n samples, then it will not be split any further.
  2. criterion=gini,entropy

Decision trees are generally prone to overfitting.

You can build bigger classifiers like ensemble methods using decision trees.

 

 

Glossary:

References:

https://www.analyticsvidhya.com/blog/2016/04/complete-tutorial-tree-based-modeling-scratch-in-python/#one

https://zyxo.wordpress.com/2010/09/17/why-decision-trees-is-the-best-data-mining-algorithm/

Computational combinatorics vs heuristics

In most of the AI algorithms, it is often the case that you enumerate in some sort and search through all the possible states and check whether we are at the goal state or particular constraints are being satisfied for the different combinations of states. This pretty much looks like a brute force and doesn’t seem to be intelligent though it could solve a pretty huge number of problems because of computational power we are endowed with. There would be a hard upper bound to the kind of problems we can tackle because of the computational limitation.

To make the search more efficient and more directional, we try to use human thought up heuristics into the search algorithms to guide the search. This is the crucial part of Human-machine interaction, leveraging the benefits of computational power and accuracy to the uniquely human-like heuristic intuition.

But the main question is, could we ever be able to make a computer think up its own heuristics appropriate to problem domain to guide its search?

Another question, How do we come up with heuristics in the first place? Do we develop it by copying the practices of our peers and mentors through our experience in the domain? or did we develop an innate sense of what to do when in some regular day to day chore settings because of millions of years of evolution? Is the ability to think up right heuristics is what true intelligence is?

Investment fundamentals

comparable analysis.PNG

Once a company is declared as publicly operating company, we can buy or sell stocks to take part in the ownership of the company based on the number of shares you hold in the total number.

The price of a share usually depends on the demand for that share. Less supply, more demand, high price. More supply, less demand, low price.

Earnings per share: This gives you the information about the profits on each share.

P/E-Price/Earnings per share ratio can be considered as right quantity to value a share. Lesser the ratio, better.

Market capital or the total value of a company = price per share * a total number of shares.

Usually, total shares remain constant, but companies can increase shares and dilute your ownership. This results in a reduction of stock price.

Sometimes this reduction in stock price can be followed by an increase in profits because of the huge initiative coming from the cash raised by new stocks.

Market cap represents the public perception of the outstanding value of a company.

Even though you analyze thoroughly and decide to buy stocks of a particular company, you need to have a seller to buy them.

Do you know what does the point stock price moves to in next instance represent? How is it determined?

The price of a stock at any given time is merely the point of equilibrium at which the number of buyers willing to buy at that price is equal to the number of sellers willing to sell at that price.

Simply put, it is just a snapshot of the last price at which a stock price was traded at.

Factors that could affect a stock price:

1. Source of earnings of a company.

2. Public perception of the value of a company which creates demand, this could happen by quarterly and annual reports on profits of a company.

3. Announcements and news related to that company which will invoke certain emotions and reactions about buying or selling at what price.
The ideal situation for profits is identifying how many people want to buy these stocks in the future but not now. You want to identify stocks which have poor demand now but will likely have lots of demand in the future.

So if you are a newbie entering the market and convey your willingness to buy a stock, it will add value to that stock price and you help all other guys holding those stocks potentially earn more if they choose to sell it.

I believe earnings in investing happens when one person having a stock predicts that a stock price goes down in future and is willing to sell it and another person who predicts the opposite and willing to buy it. Obviously, only one thing happens in a particular time frame and the guy who predicted right will be happy as long as he keeps predicting to sell it at right time.

What are the investments against inflation?

The value of money decreases as time goes by. The amount of money it required to buy a car a few years back could be far less than what it would cost now. Are there any investments that secure the value of your money against inflation?

Invest in something that is scalable in terms of both money and time.

Identify and invest in automated systems because automated systems generate passive income and more reliable.

Real estate business is mostly determined by decisions of government and corporate monopolies. If the government decides to construct a particular infrastructure in a particular place, then the land around it gains value.


Factors to be considered while analyzing stocks:

  1. Company p/e to sector p/e ratio.
  2. Who is running the company? How much of his wealth is related to his own company?
  3. Charts of previous dividends and other financial histories of the company.
  4. Whether it is a monopoly or not? Monopolies are good for long term.
  5. Income sources of the company and their stability.

While gathering data, check whether stocks have been split or not.


 

Are the company resources under optimal utility?


Dhandho investing :

  1. Identify low-risk high return investments.

Calculating the intrinsic value of a business:

  1. Extrapolate the free cash flow of future years(how long you want to hold the business) of the business based on the history of it.
  2. Discount the cash flow for the inflation of future years and add the discounted cash flow of all of them.
  3. Predict and add the future sale price of the business.
  4. This gives us an approximate estimate of the intrinsic value of the business.

Some other things to look for during investing:

Moat: How hard is it for a newcomer to start and compete with this business?

Best investments can be of two types:

Value investments: If the Market cap of the company is way lower than the intrinsic value/ net worth of the company, if the book value is more than the Current Market price, then you are getting it for cheap and probably a good investment. But before betting on these kinds of stocks, check for the durability of the business and the possibility of liquidating your investment in the future.

Growth investments: Though the Market has rightly valued the stock, the company is steadily growing at a reasonably good growth rate in terms of ROCE/ revenue/ PAT etc. then you have a steady investment.


Some things to avoid while making investments:

  1. Airline business:
    1. Why? check this video.
    2. This also teaches that understanding underlying economics is more important than anything else before investing. Even a smart management can’t turn around the boat when the economic model of the business is bad.

Good debt vs Bad debt:

  1. As long as you manage to figure out some investment that grows faster than the interest rate of of your debt and gives more returns than what you need to pay, then that is good debt.

Architecture for AGI

trans_jour

This article mainly runs on following dimensions.

  1. Perceiving the state of the world and state of yourself in the world.
    1. The power of discriminating and encapsulating different material and immaterial concepts which are often indefinitely defined, fuzzy, context -based and have no rigid boundaries.
      1. Natural language processing.
      2. Abstractions- clustering problem. Identifying the need for a level of clustering for current problem domain.importance of similarity measure in clustering. Rudimentary kind of clustering is clustering based on how different objects in the world be useful to him in what ways… Like things to eat to be clustered as one, things to talk to, things to use as the tool, or which body part to be used for what object. K-means algorithm.naive Bayes inferring classes from the models and models from the classes.em algorithm.
    2. pattern recognition.
    3. proprioception and self-referential systems.
    4. object recognition (https://www.youtube.com/watch?v=5yeusVF42K4)
    5. Donald Hoffman’s theory of perception.perceptual systems tuned to fitness outcompete those that are tuned to truth/reality.
  2. Goals and priorities in them.
    1. Switching between the goals based on the timeframes and dependencies for each goal.
    2. Inbuilt goals like getting sex, food, staying alive and goals we choose for ourselves by the culture and experiences and interaction between two kinds. Ethical issues of giving a power of creating self-goals to AI systems.
    3. Decision-making.
  3. Relevance measure for objects perceived in the world to the current goal.
    1. Prioritising perception or attention based on relevance to goal.
    2. Adaptivity of attention based on the skill level(acquired by repetition of the same process)
  4. Identifying actions or a sequence of actions to impact objects for achieving our goals.(planning)
    1. The element of stochasticity or randomness in finding the sequence is necessary to be creative when the sequence is unknown or not obvious.
    2. This can happen from analogies, empathy and copying, pattern recognition.
    3. Considering optimisation in face of multiple paths to a goal.
    4. related to imagination.
  5. A parallel Emotion machine with continuous feedback of utility or happiness on your present state in the world.
    1. Decision-making.
    2. operant conditioning.
  6. Platform knowledge: what information do we have at our birth about the world we are surrounded by and how to build it for a machine?
    1. Evolution.
    2. Jealous baby.
    3. A young baby doesn’t get surprised if a teddy bear passes behind a screen and reemerges as an aeroplane, but a one-year-old does.
    4. No categorical classification at the very beginning.
    5. As a child grows, a number of neurones decreases but a number of synapses increases.
  7. Knowledge representation, search and weights for retention(what you don’t use, you lose)
    1. Brain plasticity.
    2. Repetition and skill.
    3. Priming and classical conditioning.
    4. The DRM effect
    5. Do elements containing similar structure trigger each other.(Hofstader’s Danny in the grand canyon), pattern recognition by analogy.
    6. Reconstruction of data as memory at hippocampus with already existing memory.
    7. Procedural , episodic, semantic
    8. Representation of ideas that could be independent of language, which could allow for generalized reasoning to draw conclusions from combining ideas.
  8. Imagination at the core of knowledge, emotion machine and goals.
    1. Demis hassabis research on Imagination and memory.

What this article doesn’t talk about is:

  1. Whether a machine can have qualia even though it acts like it has general intelligence.Mary’s room. How to test qualia for a machine? Is Turing test enough for that?
  2. When did the consciousness first evolved and How?
  3. Moral implications of AGI and singularity.

Organising the interaction of all the above:

Why do I think I am talking about AGI? because we should be able to deduce any human endeavour from the interactions of above dimensions, at least from the infinitely long interactions and their orderings. Connections missed in below diagram:

  1. Goals to emotion machine.

my-agi-architecture

Deep dive (one at a time):

    1. Why object recognition is difficult?
      1. Objects defined based on purpose rather than its look or structure. We need to co-ordinate with module 3 and 7 to overcome this.
      2. We need to identify the object even though the viewpoint of it changes. When viewpoint changes, we have this problem of dimension hopping in training neural networks to recognize the object.Usually, inputs of neural networks for image recognition would be pixels, but when viewpoint changes, the input at one pixel at one training instance will be same at another pixel during different training instance. This is dimension hopping.#viewpoint_invariance.
    2. True language understanding is impossible without internal modeling the world.
  1.  Goals and priorities
  2. Relevance
  3. Planning (identifying action sequences):
  4. Emotion machine and utility:
  5. Platform knowledge: Jean Piaget, a child development psychologist argued that children create a mental model of the world around them and continuously modify that model as they interact with reality and receives feedback. He called this phenomenon as Equilibration.
    1. Infant reflexes .
    2. A child brain is less focussed with more learning rate on multitude of things, whereas an adult is more focussed, having better self control but with less learning rate.
    3. It seems true that humans come into the world with some innate abilities. some examples by steven pinker,
      1. when a human and a pet are both exposed to speech, human acquires the language whereas pet doesn’t, presumably because of some innate difference between them.
      2. Sexual preferences of men and women vary.
      3. Experimental studies on identical twins who are separated at birth and examined at later stages of life showing astonishing similarities.
      4. Do we have moral sense at birth?
    4. The above discusses about some facts on human nature at birth, but our main focus is to find Is there a seed meta-program that we are endowed with at birth which makes all other learning and behavior possible? If there exists what is it? These kinds of systems are called constructivist systems (thorisson).

Existing Cognitive Architectures: Two types

  1. Uniformity first:
    1. Soar Architecture
  2. Diversity first:
    1. ACT-R : intelligent tutoring systems are its application. John Anderson.

      Autocatalytic Endogenous Reflective Architecture (AERA)

Sigma architecture:

Architecture-requisite

Deep mind(Demis hassabis):

Deep learning + Reinforcement learning

Miscellaneous:

  1. Art is partly skill and partly stochastic.
  2. Poetry at the intersection of analogy and utility.
  3. How much of General and/or human intelligence has to do with reason? If it is fully correlated with reason and morality is built on only reason, then we and AGI has no conflict of interest as more intelligence only means more morality. #moralitynintelligence
  4. Value system guiding attention, attention setting the problem domain, problem domain looking for heuristics, heuristics guiding the search path.

Glossary:

  1. Distributed representation: Many neurones are involved in representing one concept and one neurone is involved in representing many concepts.

Artificial Intelligence

Definition: The study and design of intelligent agents, where an intelligent agent is a system that perceives its environment and takes actions that maximize its chances of success.


Agent and environment:

Rational agent: The agent which selects the action that maximizes its performance measure given its inputs or perceptions and built-in knowledge.

PEAS: Performance, Environment, Actuators, and Sensors

Types of Environment:

  1. Fully vs partially observable:
  2. Deterministic( vs stochastic): The next state of the environment is completely determined by the current state.
  3. Episodic vs sequential: Each perception-action pair can be considered as an episode.
  4. static vs dynamic:
  5. discrete vs continuous:
  6. single-agent vs multi-agent:
  7. known vs unknown:

Types of Agents in the order of increasing generality:

  1. Simple reflex agents: based on current state only. Look up the table of percepts and actions.
  2. Model-based reflex agents: based on percept history, maintains a model of the world, condition-action rules decide the action of the agent.
  3. Goal-based agents: contains goal information additional to Model-based agents.Goals decide the actions of the agent.
  4. Utility-based agents:  Utility function is the agent’s performance measure. try to increase the happiness.
  5. Learning agents:

Agent’s organisation:

  1. Atomic representation: Consider each state as a black box.
  2. Factored representation: Each state has attribute value properties.
  3. Structured representation: Relationship between objects inside a state.

Search Agents

General example problems from AI textbook:

  1. Travelling salesman problem.
  2. Route finding problem
  3. Robot navigation
  4. protein design

State space, search space and search tree.

Measures:

  1. Completeness: Can the algorithm find a solution when there exists one?
  2. Optimality: Can the algorithm find the least cost path to the solution?
  3. Time complexity: How long does it take to complete the search.
  4. Space complexity: How much memory is needed to complete the search.

Compare search

Two types of search:

  1. Uninformed: No information about the domain.
    1. Breadth-first: FIFO
      1. bfs
      2. Applications: computing shortest path when all the edge lengths are same.
    2. Depth first: LIFO
      1. dfs
      2. Depth limited is not optimal because it might return us a high-cost path on the left sub-tree without considering other low-cost paths in the right subtree.
      3. Applications: Topological ordering of directed acyclic graphs.
    3. Depth limited: Depth first with depth limit
    4. Iterative deepening: Depth limited with increasing limit, combines benefits of depth first and breadth first. First do depth first search to a depth limit n and then increase the depth and do depth first search again. diff of BFS and IDS
    5. Uniform cost: Expand least cost node first, FIFO
      1. Dijkstra’s algorithm is a variant of ucs, except that ucs finds shortest path from start node to goal node, whereas Dijkstra finds shortest path from start node to every other node.ucs and Djikshtra.Computing shortest path when edge lengths are different. Use heap data structure for speed.
      2. I doubt Google uses UCS for it’s route finding in maps. Cost between the nodes can be a mix of distance, traffic, weather etc.Maps algorithm
        1. ucs
  2. Informed: Some information about the domain and goals.
    1. Heuristics search (h(n)): Determine how close we are to the goal based on a heuristic function. Admissible heuristic thinks that the cost to the solution is less than the actual cost.
      1. Greedy search expands the node that appears to be closest to the goal. uses a heuristic function that has the information of cost from a particular node to the target node.
        1. greedy search.PNG
      2. A* search:  Consider both the heuristic that says about the cost from a node to the target node and cost to reach that node. A* search will revise it’s decision, whereas greedy search would not. This property makes greedy incomplete and A* complete.
      3. IDA*:
  3. Local search: iterative improvement algorithms by an optimization/fitness function.
    1. Hill climbing (steepest descent/ascent,greedy local search):some variants of this are:hill-climbing
      1. sideways moves – escape flat lines.
      2. Random restart – to overcome local maxima.
      3. Stochastic –
    2. Simulated annealing : from statistical physics.
    3. Local beam search – k states instead of single state.
    4. Genetic algorithms: from evolutionary biology
      1. genetic algo.PNG

Adversarial search and games:

Multiagent environment, uncontrollable opponent.

Not a sequence of actions, but a strategy or policy.

Approximation is the key ingredient in the face of combinatorial explosion.

Types of games.PNG

(perfect information, deterministic) – Zero sum games.

At any stage, one agent will try to pick the move with maximum utility out of all legal moves and the opponent will pick the move with minimum utility.

Embedded thinking or backward reasoning:

Thinking through the consequences and potential actions of the opponent before making the decision.

Minimax : Two opponents playing optimally, one trying to maximize and other trying to minimize the utility.

Alpha-Beta pruning:

When the agent that is trying to find Max utility of it’s children, you start with an alpha as (-infinity), and update alpha if you find any child nodes with utility better than present alpha. During this process, if you come across any 2nd gen childs with utility less than alpha, then you don’t need look for utilities of other 2nd gen childs of that particular 1st child. Why? because that 1st gen child is trying to find minimum, once you go down below alpha, that 1st gen child is out context at the zeroth generation which is trying to find max has found that this 1st gen child can no longer contribute to me. In this context, ordering of child nodes matters a lot. Right ordering can save you from exploring a lot of unnecessary childs/paths.

Stochastic/Non-deterministic games:

A chance/random element involved.

Expectiminimax.

Machine Learning:

Data collection -> Data preparation -> Exploratory Data analysis(picture the data using different graphs and charts) -> Machine learning techniques -> Visualization -> Decision

  1. Decision trees:
  2. Rule induction:
  3. Neural networks:
  4. SVMs
  5. Clustering method
    1. K-means
    2. Gaussian mixtures
    3. Hierarchical clustering
    4. Spectral clustering.
  6. Association rules
  7. Feature selection
  8. Visualization
  9. Graphical models
  10. Genetic algorithm

Statistics:

  1. Hypothesis testing
  2. Experimental design
  3. Anova
  4. Linear regression
  5. Logistic regression:
    1. It is a linear classifier, why?
      1. Because the decision boundary where the probability=0.5 is linear.
  6. GLM
  7. PCA

Definition of Machine learning:

A computer program is said to learn from experience E with respect to some class of tasks T and performance P, if its performance at tasks in T, as measured by P, improves with experience E.

BY its very definition, Machine learning algorithms are generally subdued to a particular class of tasks and not generic enough for general intelligence.

K-nearest neighbors:

O(n*d) – n is the number of training examples and d is the number of features.

K is usually chosen as odd value.

z-scaling – Each feature has a mean of 0 and a standard deviation of 1.

kernel regression is a flavor of k-nearest neighbors where we weight the contribution of each neighbor, whereas in k-nearest neighbor we just take the average.

Applications:

Recommender systems (collaborative filtering).

Breast cancer diagnosis

Handwritten character classification

information retrieval


 

To Avoid over fitting:

Reduce the number of features manually or do feature selection (Algorithms like random forest and XGBoost can give feature importance that you can use to prune less important features).

Do a model selection

Use regularization (keep the features but reduce their importance by setting small parameter values)

  1. Lasso regularization (L1): used in case if you want to prune some unimportant features.
  2. Ridge regularization (L2): works better than L1 usually in practice.
    1. .

Do a cross-validation to estimate the test error.

Training set used for learning the model.

The validation set is used to tune the parameters, usually to control overfitting.

Linear Models:

  1. Linear regression.
    1. Using least square loss
  2. Linear classification:
    1. Perceptron: Data has to be linearly separable.

Classification: Logistic regression

Decision Trees: Tree classifiers

Start with a set of all our examples at the top root node.

Create branches considering splitting criteria and repeat this for creating other branches as you go down.

write the final decision at the bottom of the tree based on training examples and used this tree to classify any new test data.

First, we calculate entropy at a node and then compare info gains for extending that node for different dimensions. Then we choose to extend based on the category of high info gain.

Pruning strategies to escape overfitting:

  1. Stop growing the tree earlier.
  2. Grow a complex tree and then prune it back. Remove a subtree and check it against a validation set, if the performance doesn’t degrade, remove the subtree from the original.

Cart method:

Another method to build a decision tree.

  1. Adopt same greedy, top-down algorithm.
  2. Binary splits instead of multiway splits.
  3. uses Gini index instead of information entropy.

Gini=1-p^2-P^2

p-proportion of positive examples

P-proportion of negative examples.

Bayes Rule:

Bayes rule.PNG

Discriminative Algorithms:

Idea: Model p(y/x), conditional distribution of y given x.

Find a decision boundary that separates positive from negative example.

Generative Algorithms:

modelling for Bayes rule.PNG

Naive Bayes assumes that feature values are conditionally independent given the label.

Naive Bayes classifier is linear.

Naive Bayes.PNG

Ensemble Methods:

An Ensemble method combines the predictions of many individual classifiers by majority voting.

Such individual classifiers, called weak learners, are required to perform slightly better than random.

  1. Majority voting:
    1. Condorcet’s Jury theorem:
      1. Assumptions:
        1. Each individual makes the right choice with a probability p.
        2. The votes are independent.
      2. If p>0.5, then adding more voters increases the probability that the majority decision is correct. If p<0.5, then adding more voters makes things worse.
  2. Boosting:
    1.  adaboost
    2. One of the most popular Machine learning methods.
    3. AdaBoost.M1-popular algorithm.
    4. Weak learners can be trees, perceptrons, decision stumps etc.
    5. The predictions of all weak learners are combined with a weighted majority voting.
    6. Idea: Train the weak learners on weighted training examples.AdaBoost.PNG
      1. AdaBoost with Decision stumps lead to a form of feature selection.
      2. Bootstrapping is a resampling technique for training weak learners from m samples of original training data.
    7. Iteratively give more weight on examples that are misclassified and less weight for examples that are classified properly.(Refer weight updation step d in above picture).
    8. Boosting.PNG
    9. Boosting tends to avoid overfitting because of increasing margin as you add more and more weak learners.
    10. Boosting tends to overfit if weak learners themselves are overfitting.
  3. Bagging:Bagging.PNG
    1. Bagging on trees works better than building a big tree on whole data.
  4. Random forests: Make a lot of decision trees with each tree trained on a random subset of training data and a random subset of all features considered. use the majority votes of different decision trees to determine the final outcome for a random forest. This is relying on the principle that majority of decision trees will compensate for some wrongly classifying decision trees at different instances.
    1. Quora uses random forests for determining whether two questions are duplicates.

A practical guide to applying Support Vector Classification:

Clustering examples:

  1. Clustering of the population by their demographics.
  2. Audio signal separation.
  3. Image segmentation.
  4. Clustering of geographic objects
  5. Clustering of stars.

Desirable clustering properties:

  1. Richness: For any assignment of objects to clusters, there is some distance matrix D such that a clustering scheme returns that clustering. For example, Stop when clusters are x units apart reached is rich because it can address all possible clusterings with variations of x. On the other hand, stop when a fixed number of clusters reached, is not rich because it can’t address all possible clusters.
  2. Scale invariance: Scaling distances by any value shouldn’t change the clustering of the objects.
  3. Consistency: Shrinking(making similar things more similar) intra cluster distances and expanding(making non-similar things more non-similar) inter clustering distances shouldn’t change the clustering.

Impossibility theorem: No clustering algorithm can achieve all three of richness, scale invariance, and consistency.

K-means:

  1. Based on initial conditions of the centroid, you may end up with totally different clusters. To deal with this, we take the ensemble of clusterings with different initializations. n_init parameter determines that.
  2. sklearn.cluster.KMeans(n_clusters=8,max_iter=300, n_init=10).

Limitations of k-means:

  1. Output for any given training set would always be same as long as we do not randomly pick initial centroids. But we usually choose centroids randomly in the beginning.
  2. Hill climbing algorithm.

K-means fails for:

 

Solution for How to select K.

G-means:G-Means betterment of k-means.PNG

How to evaluate?

internal evaluation: High intra-cluster similarity, Low inter-cluster similarity.

External evaluation: Mutual information, entropy, adjusted random index.

Other clustering methods:

  1. Special clustering
  2. DBSCAN
  3. BIRCH

1.Single linkage clustering:

Keep on finding two closest points among all points and join them as long as you end up with k required clusters. This is a hierarchical agglomerative cluster structure.

single linkage cluster.PNG

Association Rules:

Supp(A->C): P(A^C)

Probabilistic interpretation:

R: A->C

conf(A->C)=P(C/A)=P(A^C)/P(A)

Though this looks like a valid measure, it doesn’t take into account P(C).

Interest(A->C)=P(A^C)/(P(A)*P(C))=Conf(A->C)/supp(C)

interest(R)=1 then A and C are independent.

interest(R)>1 then A and C are positively dependent.

interest(R)

Applications:

Collaborative filtering, customer behavior analysis, web organization, affinity promotion, cross-selling

Multidimensional rules:

Read more about Quantitative Association rules as well.

CONSTRAINT SATISFACTION PROBLEMS:

Care about goal rather than the path.

intelligence_levels

Three elements:

  1. A set of variables.
  2. A set of domains for each variable.
  3. A set of constraints that specify allowable combinations of values.

Types of consistency:

  1. Node consistency – unary constraints
  2. Arc-consistency (Constraint propagation)- binary constraints – For every value that can be assigned to X, if there exists a value that can be assigned to Y, then X->Y is arc consistent. AC-3 is the algorithm that makes a CSP arc consistent. O(n^2*d^3)
  3. Path-consistency – n-ary constraints

Forward checking propagates the information from assigned to unassigned variables only and does not check the interaction between unassigned variables. Arc consistency checks for all arcs and keep doing it whenever the domain of a variable is reduced. In this sense, AC is more general and an improvement of FC.

Two types of CSPs:

  1. Search based
    1. BFS
    2. DFS
    3. BTS
  2. Inference

Choose the one with minimum remaining values to fill first.

Fill with least constraining value first – the one that rules out fewest values in remaining variables.

Can work on independent subproblems separately based on the problem structure.

Backtracking:

d-size of domain, n-number of variables.

O(d^n)

Reinforcement learning:

Learning behaviour or actions based on the rewards/feedback from environment.

Science of sequential decision making.

  1. Markov decision process – Formal model for sequential decision making.
    1. Markov property – Future is independent of the past given the current state.
    2. Applying reinforcement framework to Markov process.
    3. Theorem – Due to the Markov property, A discounted MDP always has the stationary optimal policy (pi).
    4. A policy is better than another policy if it’s value is greater than the other one calculated from all starting states.
    5. One useful fact is there always exist an optimal policy which is better than all other policies.
    6. Bellman equations.
    7. No closed form solution to Bellman equations to solve for optimal policy.
    8. other iterative solution approaches are
      1. Policy iteration.
      2. Value iteration.
    9. Think of different policies to traverse through MDP. Calculate value of each policy.
    10. Q-value iteration.
    11. Epsilon greedy exploration – with probability epsilon, take random action, with probability (1-epsilon) , take greedy action.

Logical agents or knowledge-based agents:

Mainly based on knowledge representation(domain specific) and inference(domain independent).

  1. Using propositional logic.
  2. Using First – Order Logic – used in personalized assistants.

pros and cons of Logical agents:

  1. Doesn’t handle uncertainty, probability does.
  2. Rule-based doesn’t use data, ML does.
  3. It is hard to model every aspect of the world.
  4. Models are encoded explicitly.

Resolution algorithm

Natural Language Processing:

Text classification (spam filtering)- Naive Bayes classifier.

Sentiment analysis

Naive bayes classifier – Assumes features are independent.

Classifies the new example based on the probabilities of different classes given the features of that particular example.

m-estimate of the probability:

  1. Augment the sample size by m virtual examples, distributed according to prior p.

Chain rule of probability:

  1. To estimate joint probability

N-gram model: Look N-1 words in the past to predict next word.

Bigrams capture synctactic dependencies such as noun comes after eat and verb comes after to etc.

3-grams and 4-grams are common in practice.

Perplexity – Hiigher the conditional probability, lower the perplexity.

Great progress:

Tagged text – which word is what type – noun, adjective,verb

Name entity recognition – yesterday(time), I(person), five (quantity)

Good progress:

Parsing – Exhibit the grammatical structure of a sentence.

Sentiment analysis – Does it identify sarcasm?

Machine translation

Information extraction.

work in progress:

Text summarization

Question/Answering

Dialog systems: Siri, echo etc.


Deep learning :

  1. Less or no feature engineering required.
  2. Need to choose number of layers in the stack and number of nodes in each layer.
  3. Needs to be sensitive to minute details to distinguish between two breeds of a dog and at the same time, it should be invariant to large irrevelant variations like background, lighting and pose etc.
  4. ReLU usually learns much faster in networks with many layers compared to sigmoid.
  5. Pre-training was only needed for small data sets with the revival of deep learning.
  6. Convnet combined with recurrent net to generate image captions. Vision to language interface.
  7. Handwritten characters, spoken words, faces were most succesfull applications.
  8. Theorem: No more than 2 hidden layers can represent any arbitrary region (assuming sufficient number of neurons or units).
  9. The number of neurons in each hidden layer are found by cross validation.
  10. The Mammalian visual cortex is hierarchical with 5-10 levels just for the visual system.
  11. Examples of Deep neural networks – Restricted Boltzmann machines, convolutional NN, autoencoders etc.
  12. Software for Deep learning:
    1. Tensorflow – Python
    2. Theano – Python
    3. Torch – LUA
    4. Caffe – Suited for vision

Robotics:

Path planning:

  1. Visibility graph: VGRAPH – A-star search through the nodes between obstacles. guaranteed to give shortest path in 2d. Doesn’t scale well to 3d. Path close to obstacles (nodes at vertices).
  2. Voronoi path planning:
  3. Potential field path planning: Consider both robot and obstacles as positive charges repelling each other and Goal as negative charge attracting the robot. Take a Random walk in case you reach a local minimum.
  4. Probabilistic roadmap planner: First needs to sample the space entirely and detect some collision free nodes. connect k nearest neighbor nodes. then do graph search to go from start to goal with these connected nodes. Can’t be sure that all nodes will be connected.

Glossary:

  • Discriminative models learn the (hard or soft) boundary between classes
  • Generative models model the distribution of individual class.
  • Confusion matrix.
  • ply – each move by one of the players.
  • policy – State to action mapping
  • stationary policy -Particular action for a particular state all the time.
  • Representation learning – automatically discovers representations required to classify or predict, Not much feature engineering required. Ex: Deep learning.
  • Saddle points/ minimax point – where derivative of the function is zero, but because of max in one ax and min in other axes. In the shape of the saddle on the horse.
  • Unsupervised pre-training – Making features before feeding into the learning network.
  • Configuration space(C – space): Set of parameters that completely describe the robot’s state. Proprioception.

CREDITS: Columbia University

Entrepreneurship

From first principles:

The best way to be an Entrepreneur is not try to be one until it demands.

The process of landing on an Entrepreneurship is:

  1. Just try to lead a simple lifestyle.
  2. If you face any problem in that normal lifestyle.
    1. Try to see if anybody else has solved that problem and reuse the solution and move on.
    2. If you can’t find any solution, then it must be a great opportunity that is applicable to many people like you since you were just trying to lead a regular lifestyle.
    3. Use the opportunity and create a solution for yourself first and then optimise it for quality.
    4. Market the solution for other people who would potentially come across same problem in future.

Dream garden

The idea is to help you be self sufficient in essential healthy dietary needs of your body as much as possible, by growing most of that in your own garden. The choices below of what needs to be grown in a garden are driven by Dr.Berg‘s idea of running your body on ketones(fat fuel), rather than sugar/carb fuel. The order of this list has been tried to optimise in terms of least maintenance and most benefits.

ItemBenefitsHow and where to growHow much to
eat per day
Side effectsOther comments
Moringa Miracle tree
Lemon tree
Almond tree
Broccoli
Onion
Holy Basil
Ashwagandha
Tomato
Carrot
Cucumber

Extra Diet with outside source:

1. Small fish pond.

2. Eggs.

3. Cheese

4. Oyster.

Anti-Aging focus:

  1. Herbs/spices:
    1. Anise.
    2. Cinnamon.
    3. ALLSPICE.
    4. Cloves.
    5. Oregano.

2.

Detox focus:

  1. Cauliflower.
  2. Cabbage.
  3. Kale.
  4. Arugula.
  5. Bokchoi.
  6. Brussel sprouts.
  7. Collard green.
  8. Radish.

Lose weight without any workout

Some rules or habits followed rigorously can help you lose weight without hard workouts. Some of them are:

  1. Calorie consumption should be less than calorie expenditure for each day.
  2. 16 hour fasting period for each day. Giving time for digestion and healing.
  3. Eat only if you are hungry, and don’t push hard to completely fill the stomach.
  4. Try Enema to clean your stomach.
  5. Expose yourself to sunlight for a while.
  6. Consume egg whites, very lean source of protein.
  7. Consume more fruits(less digestion time) and less grains.
  8. Drink lots of water early in the morning with empty stomach.
  9. Avoid escalator and use stairs.

One pager template to propose a new idea.

Project name: YourProject
Page maintained by: Your Name
Version: 1.0
Last update: YYYY-MM-DD

Executive Summary

A very high-level view of project (10,000 feet view). This is one paragraph briefing of what you are trying to achieve and what this project brings to customers. Targeted for high level managers, this portion should be very brief yet specific enough to buy in managers’ attention. Do not use items here and stick with a narrative paragraph.

Current State

Current state of systems and procedures which contains problem, waste, error, or potential hazard your customer experience today. This is a brief paragraph accompanied with items representing each specific issue. Back your statement of problems with metrics.

  • current issue1 (e.g. 50% of customers suffer from website loading times)
  • current issue2
  • …

Desired State

Again a brief paragraph plus items explaining the desired state. When you picture desired state do not think of how to achieve it but think of what delivers value to your customer. Draw ideal state for your customers here, specifically what features they’ll get or use-cases they can now achieve (e.g. mini Press Release benefits).

  • desired state 1 (e.g. Not even one customer suffers from load delays)
  • desired state 2
  • …

Objectives (Success Criteria)

  • Itemized list of success criteria
  • This section should be itemized and metric based
  • This is an achievable list of desired states, which you can check your project success with.
  • e.g. Website load time reduced to 10% of current delay


Project Definition

One or two small paragraphs to explain how you are achieving desired state. This is mostly explaining how you are implementing your project / procedure. Avoid very long narratives and use sections below to itemize your project.

In Scope

  • List of what you are going to deliver
  • e.g. Website loading time

Out of Scope

  • List of thing that are not in your projects scope and not related to your success criteria
  • So many things can be out of scope, use your judgement and common sense
  • e.g. Website look and feel

Dependencies

  • List of services, tools, products, procedures, policies, … your project depends on
  • …

Related Projects

  • Current projects and tools related to your projects goal
  • This is very important section as we want to find available tools that are trying to do same things and avoid reinventing the wheel
  • You may find some available tool that can be changed to deliver your goals, use them.

Benefits

  • list of benefits in a measurable and metric based statements

Costs

  • Cost items and an estimation of cost
  • e.g. One full-time full stack developer

Risks and Blockers

  • List of risks and blockers
  • e.g. release of new website next year will make this project moot
  • e.g. Project will be blocked until release of new version of Android

Milestones

  • Itemize your milestones and loose estimation of deadlines
  • e.g. Analysis of current delays in two weeks

Stakeholders

  • Your customers, beneficiaries, and other related people (except for people in the next section)

Project Team and Sponsors

  • Project team, related managers, Sponsors

High Level Test Plan

  • Describe the high level plan on how/what needs to verified for the project to assure that it is working as intended
    • E.G. – If the project relies on Apollo’s deployments to block, the project should include testing that verifies the behavior between the project functionality and Apollo
  • This should serve as a check list on what needs to be verified before releasing to Prod

References

  • List of your references and link to other resources as wiki pages, project code, …
  • Some one pager examples

The stateful code in Java

Contents

  • 1 What is stateful code?
  • 2 Stateful code is often not thread safe
    • 2.1 Try to always use “final”
    • 2.2 Consider using immutable collections
    • 2.3 Use @NotThreadSafe if your class is not thread safe
  • 3 Stateful code can be hard to maintain
  • 4 The stateful code is hard to test

What is stateful code?

The stateful code is often not thread-safe

At Amazon, we’ve had many production issues related to stateful code that didn’t have to be stateful. The more mutable state a piece of code stores, the harder it is to reason about that code. This SDE Habit will mostly talk about Java, but its advice should be applicable to other languages (feel free to add examples.)

Try to always use “final”

For member variables in particular, using “final” is almost always correct. It is not sufficient to make sure your code is thread-safe, but it is a good first step. Take a look at this piece of code as an example (note that this is a modified form of actual production Amazon code that caused real problems)

public class SQSProvider {
  private AmazonSQS client;
  private String queue;
  private String receiptHandle;
 
  public SQSProvider(AmazonSQS client, String queue) {
    this.client = client;
    this.queue = queue;
  }
 
  public Document getNextMessage() {
    // (this code is a bit simplified to illustrate the point)
    Message sqsMessage = client.receiveMessage(new ReceiveMessageRequest(this.queue));
    Document document = new Document(sqsMessage.getBody());
    this.receiptHandle = sqsMessage.getReceiptHandle();
    return document;
  }
 
  public void deleteSQSMessage() {
    client.deleteMessage(new DeleteMessageRequest(queue, receiptHandle));
  }
}

This code isn’t thread-safe. If multiple instances of it exist, they will clobber each other’s receipt handles, and start deleting each other’s messages.

It might be immediately obvious that this code isn’t thread-safe, and that if multiple threads call getNextMessage(), they will clobber each other’s receipt handle. But the fact of the matter is that a class can get complicated, and these sorts of bugs are very easy to introduce when a class starts storing state.

If the client, queue, and receiptHandle were all final, it would be immediately obvious that there was a bug in this code. The developer would realize that getNextMessage shouldn’t set the receiptHandle as a member variable, and should instead return it in Document (and deleteLatestSQSMessage() should take a Document as a parameter, or at least a receipt handle.)

Here is the fixed version of the above code:

public class SQSProvider {
  private final AmazonSQS client;
  private final String queue;
 
  public SQSProvider(final AmazonSQS client, final String queue) {
    this.client = client;
    this.queue = queue;
  }
 
  public Document getNextMessage() {
    // (this code is a bit simplified to illustrate the point)
    final Message sqsMessage = client.receiveMessage(new ReceiveMessageRequest(this.queue));
    return new Document(sqsMessage.getBody(), sqsMessage.getReceiptHandle());
  }
 
  public void deleteSQSMessage(final Document doc) {
    client.deleteMessage(new DeleteMessageRequest(queue, doc.getReceiptHandle()));
  }
}

Here are some other uses of non-final member variables that introduced real bugs in production Amazon code:

  • Having a member variable to store the content of an email. When that class started being called by multiple threads, they started overwriting each other’s contents
  • Having a member variable to store a connection to a database. This caused the connection not to be closed when running in a multi-threaded environment.

[edit][hide]Consider using immutable collections

Google Guava provides a number of utility classes that are immutable, notably ImmutableList, ImmutableMap, and others. If your class has to have a collection as a member variable, consider if it really has to ever change. If not, you should use an immutable collection.

It is a good habit to always to default your collection to these immutable options and only use a mutable collection if absolutely necessary.

[edit][hide]Use @NotThreadSafe if your class is not thread-safe

Using non-thread safe code as if it were thread-safe is often a source of defects down the line. If you must write a class which is not thread-safe, use the @NotThreadSafe java annotation to let consumers know.

@NotThreadSafe
public class SQSProvider {
}

If you know that your code is non-thread safe and “by design”, you know you will not make it thread-safe, then @NotThreadSafe is the appropriate annotation to use. Code which has no annotation should probably be assumed to be not thread-safe. If you can confirm that a given piece of code is thread-safe, you should add @ThreadSafe —Olivwong 19:53, 17 January 2014 (UTC)

Stateful code can be hard to maintain

Whenever expending engineering resources to develop a piece of technology, consider whether it is worth it for you to devote engineering resources to maintaining that piece of software.

At Amazon, it is often correct to let a dedicated team maintain your state. There are many different technologies available (see the Storage wiki for a full run-down on your options.) But before you go and create a HashMap (or *insert other homegrown state management* methodology) in your code to store some state, think about whether or not you’ve considered all the edge cases:

  • What if that HashMap grows infinitely?
  • What if a box dies and comes back online?
  • How do you handle deployments?

Sometimes it is OK to store state in your own code, but many teams have had great success offloading that state management to others. For example, AWS services do a great job of managing state, and can greatly simplify your application (if they’re a good fit.)

The stateful code is hard to test

Imagine the above example of the SQSProvider class. If you want to test the deleteSQSMessage() method, you would have to always call getNextMessage() first since the deleteSQSMessage() refers to the state that is only set in the getNextMessage() method call.

By introducing state into your code, it makes it harder to test individual components of your code. In addition, it can be difficult to make fully reproducible test cases, since each test case will need to make sure it stores the same state each time it runs.

Effective Java : Serialization

Serialization

Objective: This section explains the dangers of serialization and how to minimize them. Object serialization is Java’s useful framework for encoding objects as byte streams (serializing) and reconstructing objects from their encodings (deserializing). Once objects have been serialized, they can be sent from one virtual machine to another or stored on disk for later deserialization.

Key topics:

  1. Java Serialization
  2. Custom Serialization
  3. Serialization and Security
  4. Serialization and Instance Control
  5. Serialization Proxy

Estimated time: 15-30 minutes.

Java Serialization

Can you spot a problem when you deserialize the following byte stream?

static byte[] createByteStream() {
Set<Object> root = new HashSet<>();
Set<Object> s1 = root;
Set<Object> s2 = new HashSet<>();
for (int i = 0; i < 100; i++) {
Set<Object> t1 = new HashSet<>();
Set<Object> t2 = new HashSet<>();
t1.add(“beer”); // t1 is NOT equal to t2
s1.add(t1); s1.add(t2);
s2.add(t1); s2.add(t2);
s1 = t1;
s2 = t2;
}
return serialize(root); // Method omitted for brevity
}

 Yes
 No

It is difficult to spot the problem when you deserialize the above stream, just by reading the code. The above object graph consists of 203  HashSet instances, each of which contains 3 or fewer object references. The entire stream is 5,744 bytes long, yet the sun would burn out before you could deserialize it! To understand what happens, note that deserializing a  HashSet  instance requires computing the hash codes of all of its elements. The 2 elements of  root  are also hash sets that contain 2 hash-set elements, each of which contains 2 hash-set elements, and so forth, 100 levels deep! Hence,  hashCode  method will be invoked over 2100 times to deserialize  root , OUCH! So, you should avoid using Java serialization wherever possible; you should use a cross-platform, structured-data representation such as JSON instead. If you must use Java serialization then you should NOT deserialize any byte stream that you don’t trust, by creating a whitelist of trusted classes instead of a blacklist of untrusted classes (by default you should reject classes that are not included in the whitelist).

If you choose to implement  Serializable  interface, however, you must be absolutely aware of what you are doing. Here are some major costs of doing so:

  • It decreases the flexibility to change your class’s implementation once it has been released, because its byte-stream encoding or serialized formbecomes part of its exported API and you must support it forever.
  • It increases the likelihood of bugs and security holes, because it provides an extralinguistic mechanism for clients to create instances of your class.
  • It increases the testing burden associated with releasing a new version your class, because of backward compatibility, meaning that you must ensure that the new version of your class can deserialize the serialized form of the old version and vice versa.

    Here are some recommendations you should consider before you decide to implement  Serializable  interface:

  • Classes designed for inheritance should rarely implement  Serializable , because you don’t, actually cant’, know what its subclasses will do.
  • Inner classes should not implement  Serializable , because the default serialized form of an inner class is ill-defined. You can, however, implement the interface for a static member class.

Custom Serialization

Which of the following implementations of  StringList  would be better? Of course, ignore for the moment that you would probably better off using one of the standard  List  implementations.

 Use default serialized forms

public final class StringList implements Serializable {
private int size = 0;
private Entry head = null;

private static class Entry implements Serializable {
String data;
Entry next;
Entry previous;
}
… // Remainder omitted
}

 Use custom serialized forms

public final class StringList implements Serializable {
private int size = 0;
private Entry head = null;

private static class Entry {
String data;
Entry next;
Entry previous;
}

public final void add(String s) { … }

private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(size);
for (Entry e = head; e != null; e = e.next)
s.writeObject(e.data);
}

private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
int numElements = s.readInt();
for (int i = 0; i < numElements; i++)
add((String) s.readObject());
}
… // Remainder omitted
}

You should use the default serialized form only if an object’s physical representation is identical to its logical content, such as a  Person  object that contains first and last names. In the above example, you should use the custom serialized  form because logically  StringList  represents a sequence of strings but physically it represent a sequence of a doubly linked list. Note that using the default serialized form when an object’s physical representation differs substantially from its logical content has the following advantages:

  • It permanently ties the exported API to the current internal representation, and you must support it forever. For example, in the above example  StringList.Entry  class becomes part of the public API unnecessarily.
  • It can consume excessive space, sometimes cause stack overflow, and make serialization slow. In the above example, links of the doubly linked list will take a lot of space and time to serialize/deserialize them, again unnecessarily.

Here are some other recommendations:

  • You often must implement  readObject  method to ensure invariants and security, even if you decide to choose the default serialized form. For example, transient fields (i.e., not included in serialization) will be initialized to their default values when an instance is deserialized (  null  for object reference fields,  zero  for numeric primitive fields, and  false  for boolean fields). If these values are unacceptable for any transient fields then implementing  readObject  would be a good way to restore them to acceptable values.
  • Before deciding to make a field nontransient (i.e., included in serialization), convince yourself that its value is part of the logical state of the object, so as to avoid complications such as the one mentioned above.
  • In any case, you should impose any synchronization on object serialization that you would impose on any other method that reads the entire state of the object.
  • In any case, you should declare an explicit, static, final, long serialVersionUID in every serializable class you write, just in case you want to break compatibility, though not recommended, with all existing serialized instances of your class.
  • Use  @serial  tag for fields and  @serialData  tag for methods to document your serializable class properly.

Serialization and Security

The following implementation preserves the class’s invariants and immutability by defensively copying  Date  object in its constructor and accessors, before it is serializable:

public final class Period implements Serializable {
private final Date start;
private final Date end;

public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException(start + ” after ” + end);
}

public Date start() { return new Date(start.getTime()); }
public Date end() { return new Date(end.getTime()); }
… // Remainder omitted
}

After it is serializable, just by easily adding  implements Serializable  to the class declaration,  readObject  method is effectively another public constructor. So, if you use a default serialized form then you get into a big trouble, because that default method fails to do check validity of its arguments and make defensive copies of parameters where appropriate, meaning that you open the door for an attacker to violate the class’s invariants. Therefore, you must implement custom  readObject . Which of the following implementations would be safe? Why?

 Keep it simple

private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (start.compareTo(end) > 0)
throw new InvalidObjectException(start + ” after ” + end);
}

 Be extremely defensive

private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
start = new Date(start.getTime());
end = new Date(end.getTime());
if (start.compareTo(end) > 0)
throw new InvalidObjectException(start + ” after ” + end);
}

When an object is serialized, it is crucial to copy any field containing an object reference that a client must not possess, otherwise you open the door for an attacker to violate the class’s invariants.  Note that the defensive copy is performed prior to the validity check, otherwise the class can be subject to an attack between the time of validity check and the time of defensive copy in a multi-thread circumstance. Note also that using  Date.clone is not safe because attackers can use a subclass of  Date  and you don’t/can’t know what the subclass’s clone method behaves. Additionally, to use the second implementation above, you must make  start  and  end  nonfinal; which is unfortunate but it is the lesser of the two evils.

Serialization and Instance Control

Which of the following implementations would be safe? Why?

 Use Enum

public Enum MichaelJackson {
INSTANCE;
private String[] favoriteSongs = { “Black and White”, “Billie Jean”, “Beat it” };

public void printFavorites() { System.out.println(Arrays.toString(favoriteSongs)); }
}

 Use readResolve

public class MichaelJackson implements Serializable {
public static final MichaelJackson INSTANCE = new Elvis();
private MichaelJackson() { }
private String[] favoriteSongs = { “Black and White”, “Billie Jean”, “Beat it” };

public void printFavorites() { System.out.println(Arrays.toString(favoriteSongs)); }

private readResolve() { return INSTANCE; }
}

The second implementation opens the door for an attacker to secure a reference to the serialized object before its  readResolve  method is run. The attack is somewhat complicated, but it is based on a simple idea that if a singleton contains a nontransient object reference field then the contents of this field will be deserialized before the singleton’s  readResolve  method is run, regardless wether you use default or custom serialized form. This property enables the attacker to steal a reference to the originally deserialized singleton at the time the contents of the object reference field are deserialized. Therefore, use enum type to enforce instance control invariants wherever possible. If you must, however, implement  readResolve  method for a serializable and instance-controllable class then ensure that all of the class’s instance fields are either primitive or transient.

Serialization Proxy

Which of the following implementations would be preferable? Why?

 Use serialization proxy

public final class Period implements Serializable {
private final Date start;
private final Date end;

public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException(start + ” after ” + end);
}

public Date start() { return new Date(start.getTime()); }
public Date end() { return new Date(end.getTime()); }

private Object writeReplace() { return new SerializationProxy(this); }

private void readObject (ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException(“Proxy required”);
}

private static class SerializationProxy implements Serializable {
private static final long = 982423404852382358L; // Any number would be fine

private final Date start;
private final Date end;

SerializationProxy (Period p) {
this.start = p.start;
this.end = p.end;
}

private Object readResolve() { return new Period(start, end); }
}
… // Remainder omitted
}

 Be extremely defensive

public final class Period implements Serializable {
private Date start;
private Date end;

public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException(start + ” after ” + end);
}

public Date start() { return new Date(start.getTime()); }
public Date end() { return new Date(end.getTime()); }

private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
start = new Date(start.getTime());
end = new Date(end.getTime());
if (start.compareTo(end) > 0)
throw new InvalidObjectException(start + ” after ” + end);
}
… // Remainder omitted
}

The serialization proxy pattern above is reasonably straightforward and has been useful whenever you find yourself having to write  readObject and  writeObject  on a class that is not extendable by its clients. This pattern would be the easiest way to serialize nontrivial invariants robustly. Here are some advantages of this pattern:

  • It will never generate a serialized instance of the enclosing class or leak references of its nontransient fields, making the enclosing class safe.
  • It utilizes existing constructors/static factories of the enclosing class.
  • Its nontransient fields can be declared as  final .

Note, however that, the pattern has two main limitations, as follows:

  • It is not compatible with classes that are extendable by their clients. It is also not compatible with some classes whose object graphs contain circularities, because it you attempt to invoke a method on such an object from within its proxy’s  readResolve  method then you’ll get  ClassCastException  because you have only the object’s serialization proxy but not the object yet.
  • The added power and safety of the proxy come with some little more cost: the first implementation above could be 10-20% slower than the second one.

Effective Java : Concurrency

Concurrency

Objective: Threads enable multiple tasks to proceed concurrently. Concurrent programming is more difficult than single-threaded one because more things can go wrong, and it is hard to reproduce failures. But concurrency is a must in modern programming to utilize multicore processors! This section provides advice to help you write clear, correct, well-documented concurrent programs.

Key topics:

  1. Synchronize Access to Sharable Mutable Data
  2. Excessive Synchronization
  3. Concurrentcy Utilities
  4. Concurrentcy and Lazy Initialization

Estimated time: 15-30 minutes.

Synchronize Access to Sharable Mutable Data

Which program below won’t stop as expected?

 Don’t use volatile

public class StopThread {
private static boolean stopRequested;

public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
int i = 0;
while (!stopRequested) i++;
});
thread.start();

TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}

 Use volatile

public class StopThread {
private static volatile boolean stopRequested;

public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
int i = 0;
while (!stopRequested) i++;
});
thread.start();

TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}

Can you spot a bug in one of the following snippets?

 Use volatile

private static volatile int nextSerialNumber = 0;

public static int generateSerialNumber() {
return nextSerialNumber++;
}

 Use atomic facilities

private static final AtomicLong nextSerialNumber = new AtomicLong();

public static long generateSerialNumber() {
return nextSerialNumber.getAndIncrement();
}

When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization, otherwise there is no guarantee that one thread’s changes of the data will be visible to other threads, and therefore may cause liveness and safety failures. These failures are among the most difficult to debug. In the first example above, the use of  volatile  is a correct alternative for synchronization because you need only inter-thread communication, but not mutual exclusion. Without its use, the thread won’t stop, causing a liveness failure. But in the second example, its use is inappropriate because the increment operator (++) is not atomic. It performs two operations on  nextSerialNumber : (1) it reads the value, (2) it writes back a new value that is equal to the old value plus one. If a second thread reads the field between the time the first thread reads the old value and writes back the new one, then both threads will see the same value and thus return the same serial number, OUCH; this is a safety failure.

Note that the best way to avoid safety failure is not to share mutable data, meaning share only immutable data or don’t share at all — confine mutable data to a single thread. If you adopt this policy then you should document it carefully, so that the policy is maintained as your program evolves. It is also crucial to have a deep understanding of the frameworks and libraries you’re using because they may introduce threads that you are unaware of.

Excessive Synchronization

Assume that you are implementing an observable set wrapper that enables clients to subscribe/unsubscribe to notifications when elements are added to the set or removed from the set, as follows:

@FunctionalInterface public interface  SetObserver<E> {
void added(ObservableSet<E> set, E element);
}

public class ObservableSet<E> extends ForwardingSet<E> {
…
private final List<SetObserver<E>> observers = new ArrayList<>();

public void addObserver(SetObserver<E> observer) { … }
public void removeObserver(SetObserver<E> observer) { … }

private void notifyElementAdded(E element) { … }

@Override public boolean add(E element) {
boolean added = super.add(element);
if (added)
notifyElementAdded(element);
return added;
}
…
}

// An example of use of ObservableSet
public static void main(String[] args] {
ObservableSet<Integer> set = new ObservableSet<>(new HashSet<>());
set.addObserver(new SetObserver<>() {
public void added(ObservableSet<Integer> s, Integer e) {
System.out.println(e);
if (e == 5)
s.removeObserver(this);
}
});
for (int i = 0; i < 10; i++)
set.add(i);
}

Can you spot a bug in one of the following implementations of  notifyElementAdded ?

 Do not use snapshot of observers

private void notifyElementAdded(E element) {
synchronized(observers) {
for (SetObserver<E> observer : observers)
observer.added(this, element);
}
}

 Use snapshot of observers

private void notifyElementAdded(E element) {
List<SetObserver<E>> snapshot = null;
synchronized(observers) {
snapshot = new ArrayList<>(observers);
}
for (SetObserver<E> observer : snapshot)
observer.added(this, element);
}

 observer.added  is an alien method from clients for which you don’t, actually can’t, know how it works. So, you should be better off NOT including any alien method invocation in your synchronized code. The first implementation above will throw a  ConcurrentModificationException because  notifyElementAdded  is in the synchronized/locked process of iterating over  observers  when it invokes the observer’s  added  alien method, which calls the observable set’s  removeObserver  method, which in turn calls  observers.remove  method. This example shows only an exception problem, but in other circumstances it may cause catastrophic issues such as deadlock.

It is usually not too difficult to fix the sort of above problems by moving alien method invocations out of synchronized blocks such as the second implementation above. Note that this implementation can be improved by using  CopyOnWriteArrayList  from  java.util.concurrent  package. You should utilize this package when working on concurrency. Here are some other best practices:

  • You should do as little work as possible inside synchronized regions: obtain the lock, examine shared data, transform it if necessary, and drop the lock. If you must perform time-consuming tasks then find a way to move them out of synchronized blocks without violating guidelines in the previous sub-section.
  • If you are writing a mutable class, you can omit all synchronization, document that the class is not thread-safe, and allow clients to synchronize externally if they want to.  StringBuilder  and  ThreadLocalRandom  follow this guideline.
  • If you are writing a mutable class, you should choose to synchronize internally only if you can achieve significantly higher concurrency. And if you do so, you should use good techniques such as lock splitting, lock stripping, and nonblocking concurrency control. Classes in  java.util.concurrent  package follow this guideline.

Concurrency Utilities

Which of the following implementations that simulate the behavior of  String.intern  is faster?

 Don’t use Map.get

private static final ConcurrentMap<String, String> map = new ConcurrentHashMap<>();

public static String intern(String s) {
String previousValue = map.putIfAbsent(s, s);
return previousValue == null ? s : previousValue;
}

 Use Map.get

private static final ConcurrentMap<String, String> map = new ConcurrentHashMap<>();

public static String intern(String s) {
String result = map.get(s);
if (result == null) {
result = map.putIfAbsent(s);
if (result == null)
return s;
}
return result;
}

The second implementation could be six times faster than the first one, because  ConcurrentHashMap  is optimized for retrieval operations such as  get . You should have a deep understanding of  java.util.concurrent  package, to be able to utilize its many concurrent utilities. Here are some other recommendations:

  • Prefer executors, tasks, and streams, to threads wherever possible.
  • Prefer  ConcurrentHashMap  to  Collections.synchronizedMap .
  • If you have to use lock fields, you should always declare them as  final .
  • If you have to fix a program that barely works (e.g., some of its threads are unnecessarily runnable) then don’t depend on thread scheduler (e.g., rely on  Thread.yield  or thread priorities, because the resulting program will be neither robust nor portable. You should consider to restructure the application, by using guidelines in this section, to reduce the number of concurrently runnable threads.

Whether or not you choose concurrent utilities to avoid implementing internal synchronization, you should always document what level of thread safety it supports, so as to enable safe concurrent use of your class. Here are some common levels:

  • Immutable: No external synchronization is necessary. Examples include  String ,  Long , and  BigInteger .
  • Unconditionally thread-safe: Instances of this lass are mutable, but no external synchronization is necessary because the class has sufficient internal synchronization. Examples include  AtomicLong  and  ConcurrentHashMap .
  • Conditionally thread-safe: Like conditionally thread-safe, but some methods require external synchronization. Examples include collections returned by  Collections.synchronized  wrappers, whose iterators require external synchronization.
  • Not thread-safe: Instances of this class are mutable, and to use them clients must surround each method invocation or invocation sequence with external synchronization. Examples include general-purpose collections such as  ArrayList  and  HashMap .
  • Thread-hostile: This class is unsafe for concurrent use; it must be fixed or deprecated. Examples include  generateSerialNumber  at the beginning of this section.

Concurrency and Lazy Initialization

Which of the following implementations would be preferable?

 Use synchronized accessors

private FieldType field;

private synchronized FieldType getField() {
if (field == null)
field = computeFieldValue();
return field;
}

 Use single-check idiom

private volatile FieldType field;

private FieldType getField() {
FieldType result = field;
if (result == null) // Single check, no locking
field = result = computeFieldValue();
return field;
}

 Use double-check idiom

private volatile FieldType field;

private FieldType getField() {
FieldType result = field;
if (result == null) { // First field check, no locking
synchronized(this) {
if (field == null) // Second field check, with locking
field = result = computeFieldValue();
}
}
return field;
}

In general, you should initialize most fields normally, such as  private final FieldType field = computeFieldValue(); . If you have to initialize a field lazily to achieve your performance goals or to break a harmful initialization circularity, then use an appropriate lazy initialization technique. Use the double-check idiom for instance fields (see the third implementation above), or use the single-check idiom if you can tolerate repeated initialization (see the second implementation above). For static fields, however, use the holder class idiom, as follows:

private static class FieldHolder {
static final FieldType field = computeFieldValue();
}

private static FieldType getField() {
return FieldHolder.field;
}

Effective java : Lambdas and Streams

Lambdas and Streams

Objective: In Java 8, functional interfaces, lambdas, method references, along with streams API were added to help software engineers create function objects and process sequences of data elements more easily. This section explains best practices of how to utilize those facilities.

Key topics:

  1. Lambdas and Anonymous Classes
  2. Lambdas and Method References
  3. Lambdas and Functional Interfaces
  4. Streams
  5. Streams and Collections
  6. Parallel Streams

Estimated time: 15-30 minutes.

Lambdas and Anonymous Classes

Which of the following implementations would be more readable?

 Use lambda expressions

Collections.sort(words, (w1, w2) -> Integer.compare(w1.length(), w2.length()));

 Use function objects

Collections.sort(words, new Comparator<String>() {
public int compare(String w1, String w2) {
return Integer.compare(w1.length(), w2.length();
}
});

In general, lambdas are by far the best way to represent small functional objects because it makes the code less verbose and thus more readable. In the above example, the compiler can deduce the types of parameters, but if in other situations it throws an error then you can add them easily. Note that few software engineers understand how the rules for type reference work but it is okay. Note also that lambdas lack names and documentation; so, if a computation isn’t self-explanatory, or exceeds few lines, then don’t use them. Furthermore, lambdas share with anonymous classes the property that you can’t reliably serialize and deserialize them across implementations; hence, don’t use them, but use an instance of a private static nested class, if you want to do so.

Lambdas and Method References

The goal of the following code snippets is to associate 1 with the key if it is not in the map; otherwise increment the associated value. Which snippet would be more readable?

 Use lambda expressions

map.merge(key, 1, (count, incr) -> count + incr);

 Use method references

map.merge(key, 1, Integer::sum);

Method references often provide a more succinct alternative to lambdas; therefore, use the former wherever they are shorter and clearer than the latter. Here are some common method references:

  •  Integer::parseInt : A static method reference for  str -> Integer.parseInt(str) .
  •  Instant.now()::isAfter : A bound method reference for  Instance i = Instant.now(); t -> i.isAfter(t) .
  •  String::toLowerCase : An unbound method reference for  str -> str.toLowerCase() .
  •  TreeMap<K,V>::new : A class constructor for  () -> new TreeMap<K,V> .
  • int[]::new : An array constructor for  len -> new int[len] .

Lambdas and Functional Interfaces

You can use  LinkedHashMap  class as a cache. If you were the designer of this class, which of the following implementations would you prefer?

 Use protected methods

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
…
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return false; }
…
}

// Example of how to use LinkedHashMap
…
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>() {
// This method is invoked by put and putAll after inserting a new entry into the map.
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > 120;
}
};
…

 Use standard interfaces

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
…
// removeEldestEntry.test is invoked by put and putAll after inserting a new entry into the map.
public LinkedHashMap(BiPredicate<Map<K,V>, Map.Entry<K,V>> removeEldestEntry) { … }
…
}

// Example of how to use LinkedHashMap
…
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>((m, e) -> return m.size() > 120);
…

 Use my functional interfaces

// Always annotate your functional interfaces with @FunctionalInterface
@FunctionalInterface interface EldestEntryRemovalFunction<K,V> {
boolean remove(Map<K,V> map, Map.Entry<K,V> eldest);
}

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
…
// removeEldestFunction.remove is invoked by put and putAll after inserting a new entry into the map.
public LinkedHashMap(EldestEntryRemovalFunction<K,V> removeEldestFunction) { … }
…
}

// Example of how to use LinkedHashMap
…
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>((m, e) -> return m.size() > 120);
…

You should utilize lambdas facility when you design your APIs, meaning accept functional interface types on input and return them on output. In general, you should use standard interfaces in  java.util.function . You don’t have to memorize them but should know some fundamental ones, as follows:

Interface Function Signature Example
 UnaryOperator<T>   T apply(T t)   String::toLowerCase 
 BinaryOperator<T>   T apply(T t1, T t2)   BigInteger::add 
 Predicate<T>  boolean test(T t)   Collection::isEmpty 
 Function<T>   R apply(T t)   Arrays::asList 
 Supplier<T>   T get()   Instant::now 
 Consumer<T>  void accept(T t)   System.out::println 

Note that there are many variants of the above interfaces to operate on primitive types  int ,  long , and  double . You should use them wherever possible because the performance consequences of using boxed primitives for batch operations can be deadly. Note also that our old friend  Comparator<T> , which is structurally identical to  ToIntBiFunction<T,T>  interface, has been very popular and provides excellent self-documentation every time it is used in an API. Hence, you should consider using  Comparator<T>  first before deciding if you should try functional interfaces.

Streams

You are writing a program to read words from a dictionary and print all the anagram groups whose size meets a user-specified minimum. Which of the following implementations would be preferable?

 Use streams and helper methods

public class Anagrams {
public static void main(String[] args) throws IOException {
Path dictionary = Paths.get(args[0]);
int minGroupSize = Integer.parseInt(args[1]);
try (Stream<String> words = Files.lines(dictionary)) {
words.collect(groupingBy(word -> alphabetize(word))).values().stream()
.filter(group -> group.size() >= minGroupSize)
.forEach(g -> System.out.println(g.size() + “: ” + g));
}
}

private static String alphabetize(String word) {
return new String(Arrays.sort(word.toCharArray()));
}
}

 Use streams only

public class Anagrams {
public static void main(String[] args) throws IOException {
Path dictionary = Paths.get(args[0]);
int minGroupSize = Integer.parseInt(args[1]);
try (Stream<String> words = Files.lines(dictionary)) {
words.collect(groupingBy(word -> word.chars().sorted()
.collect(StringBuilder::new,
(sb, c) -> sb.append((char) c),
StringBuilder::append)
.toString()))
.values().stream()
.filter(group -> group.size() >= minGroupSize)
.map(group -> group.size() + “: ” + group)
.forEach(System.out::println);
}
}
}

A stream pipeine consists of a source stream followed by zero or more intermediate operations and one terminal operation. The purpose of the former is to transform one stream into another, such as mapping each element to a function of that element or filtering out all elements that do not satisfy some condition. The goal of the latter is to perform a final/return computation on the stream resulting from the last intermediate operation. Here are some things you should know about streams:

  • Stream pipelines are evaluated lazily, meaning that evaluation starts only after the terminal operation is invoked and data elements that are not required in the computation of the terminal operation will be never evaluated. This property enables you to work with infinite streams. Note that a stream pipeline without a terminal operation is a silent no-op; so, you would be better off always implementing this operation.
  • Streams API is fluent, allowing you to make multiple calls on one or multiple pipelines in a single expression.
  • By default, stream pipelines run sequentially. It is possible to make it run in parallel, but this is a rare case.
  • You should only use  forEach  as the terminal operation to report the result of a computation, not to perform the computation.
  • The essence of programming streams pipelines is side-effect-free function objects. You should be familiar with important collector factories such as  toList ,  toSet ,  toMap ,  groupingBy , and  joining .
  • Some tasks are best accomplished with streams, and others with iteration; in many cases, combining the two approaches would be preferable. The first implementation above is preferable because it is more readable and maintainable than the second one that overuses streams.

Streams and Collections

Which of the following implementations would be preferable if the size of the input list is large?

 Return streams

// Returns a stream of all sublists of its input list
public class SubLists {
public static <E> Stream<List<E>> of(List<E> list) {
return Stream.concat(Stream.of(Collections.emptyList()),
prefixes(list).flatMap(SubLists::suffixes));
}

private static <E> Stream<List<E>> prefixes(List<E> list) {
return IntStream.rangeClosed(1, list.size()).mapToObj(end -> list.subList(0, end));
}

private static <E> Stream<List<E>> suffixes(List<E> list) {
return IntStream.range(0, list.size()).mapToObj(start -> list.subList(start, list.size()));
}
}

 Return collections

// Returns a collection of all sublists of its input list
public class SubLists {
public static <E> Collection<List<E>> of(List<E> list) {
int n = list.size();
List<List<E>> result = new ArrayList<>(n * (n-1) / 2 + 1);
for (int i = 0; i < n; i++)
for (int j = i + 1; j <= n; j++)
result.add(list.subList(i, j));
result.add(Collections.emptyList());
return result;
}
}

The above problem is an exceptional case where returning a stream in the first implementation would be preferable because although the second one looks simpler, the memory required to hold the return collection is quadratic in the size of the input list, which is unacceptable for large input lists.

Generally, when you write a method that returns a sequence of elements, note that some of your clients may want to process them as a stream while others may want to iterate over them. You should try to accommodate both groups by returning a collection if reasonable. If it is too costly to do so, like the above example however, then consider to return a  Stream  or  Iterable , whichever seems more natural. If future releases of Java modify  Stream  interface to extend  Iterable  then feel free to return  Stream  because it will allow clients to process the return as a stream or as an iteration.

Parallel Streams

Can you spot a problem in the following method?

// Generate the first 20 Mersene primes in the form of 2^p – 1 where p is a prime number
Stream.iterate(TWO, BigInteger::nextProbablePrime)
.parallel()
.map(p -> TWO.pow(p.intValueExact()).subtract(ONE)
.filter(mersene -> mersene.isProbablePrime(50))
.limit(20)
.forEach(System.out::println);

 Yes
 No

Which of the following implementations would be faster?

 Use parallel streams

static long numberOfPrimes(long n) {
return LongStream.rangeClosed(2, n)
.parallel()
.mapToObj(BigInteger::valueOf)
.filter(i -> i.isProbablePrime(50)
.count();
}

 Do not use parallel streams

static long numberOfPrimes(long n) {
return LongStream.rangeClosed(2, n)
.mapToObj(BigInteger::valueOf)
.filter(i -> i.isProbablePrime(50)
.count();
}

In general, do not even attempt to parallelize a stream pipeline unless you have a very good reason that it will preserve the correctness of the computation and increase its performance, otherwise it can cause liveness and/or safety failures or performance disaster. If you choose to do it then you should ensure that your code remains correct when run in parallel, and you should collect performance metrics under realistic conditions to justify your decision. Under the right circumstances, it is possible to achieve near-linear speedup in the number of processor cores simply by adding a parallel  call to a stream pipeline. Here are things you should consider before you choose to parallelize a stream pipeline:

  • It is unlikely to increase performance of a stream pipeline if its source is from  Stream.iterate , or the intermediate operation  limit  is used. In the first example above, the pipeline has to contend with both problems and the streams library has no idea how to parallelize the pipeline.
  • As a rule, it is likely to gain performance on streams over instances of  ArrayList ,  HashMap ,  HashSet ,  ConcurrentHashMap ;  arrays ;  int  ranges; and  long  ranges; because they can be accurately and cheaply split into subranges of any desired size, making it easy to divide work among parallel threads. In the second example above, the parallel stream can be 3 to 4 times faster than the other one on a quad-core machine.