Real time stream processing presentation at General Assemb.lyVarun Vijayaraghavan
Real-time stream processing systems are useful for analyzing continuous data streams to gain instant insights. They need to be fast, scalable, and fault tolerant. Apache Storm is a popular open-source stream processing system that uses task parallelism. In Storm, spouts act as data sources, bolts perform processing tasks, and topologies define the graph of spouts and bolts. An example topology counts word occurrences in sentences from a random sentence spout. The Lambda architecture combines real-time and batch processing layers to provide both instant and reliable insights from streaming data. Apache Spark can also be used for stream processing using microbatches.
This document discusses connecting Python programs to databases. It covers:
1. Importing database modules for MySQL and PostgreSQL.
2. Establishing a connection to the database using connect() and handling connection errors.
3. Creating a cursor object to execute SQL commands.
4. Executing SQL queries like SELECT and INSERT using the cursor's execute() method.
5. Fetching data from the database using cursor methods like fetchall(), fetchmany(), and fetchone().
Cryptographic Hash Function using Cellular AutomataEditor IJCATR
This document proposes a cryptographic hash function that uses cellular automata. It introduces cellular automata and how they work. The proposed hash function takes a file as input and divides it into blocks of 128 bits. Each block is hashed using elementary cellular automata rules based on the previous block's output. The blocks are iteratively reduced in size until a single 128-bit hash value remains, providing a fixed-size digest of the variable-length input file. The hash function is sensitive to changes in the input, making it suitable for applications like detecting unauthorized file modifications.
This document discusses different frameworks for big data processing at ResearchGate, including Hive, MapReduce, and Flink. It provides an example of using Hive to find the top 5 coauthors for each author based on publication data. Code snippets in Hive SQL and Java are included to implement the top k coauthors user defined aggregate function (UDAF) in Hive. The document evaluates different frameworks based on criteria like features, performance, and usability.
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015Till Rohrmann
Apache Flink is an open source platform for distributed stream and batch data processing. It provides APIs called DataStream for unbounded streaming data and DataSet for bounded batch data. Flink runs streaming topologies that allow for windowing, aggregation and other stream processing functions. It supports exactly-once processing semantics through distributed snapshots and checkpoints. The system is optimized for low latency and high throughput streaming applications.
The document discusses various data structures including skip lists, AVL trees, and hashing. It explains that skip lists allow for logarithmic-time operations and are simple to implement. Hashing provides constant-time operations by mapping keys to array indices via a hash function, but collisions must be handled. Common hash functions discussed include summing character codes or converting to a number in a prime base.
An AVL tree, ordered by key insert: a standard insert; (log n) find: a standard find (without removing, of course); (log n) remove: a standard remove; (log n)
Apresentado no TDC Florianópolis - 2016.
Palestra voltada aos que ouviram falar sobre RxJava e querem aprender sobre a biblioteca que todos os programadores legais estão comentando.
Real time stream processing presentation at General Assemb.lyVarun Vijayaraghavan
Real-time stream processing systems are useful for analyzing continuous data streams to gain instant insights. They need to be fast, scalable, and fault tolerant. Apache Storm is a popular open-source stream processing system that uses task parallelism. In Storm, spouts act as data sources, bolts perform processing tasks, and topologies define the graph of spouts and bolts. An example topology counts word occurrences in sentences from a random sentence spout. The Lambda architecture combines real-time and batch processing layers to provide both instant and reliable insights from streaming data. Apache Spark can also be used for stream processing using microbatches.
This document discusses connecting Python programs to databases. It covers:
1. Importing database modules for MySQL and PostgreSQL.
2. Establishing a connection to the database using connect() and handling connection errors.
3. Creating a cursor object to execute SQL commands.
4. Executing SQL queries like SELECT and INSERT using the cursor's execute() method.
5. Fetching data from the database using cursor methods like fetchall(), fetchmany(), and fetchone().
Cryptographic Hash Function using Cellular AutomataEditor IJCATR
This document proposes a cryptographic hash function that uses cellular automata. It introduces cellular automata and how they work. The proposed hash function takes a file as input and divides it into blocks of 128 bits. Each block is hashed using elementary cellular automata rules based on the previous block's output. The blocks are iteratively reduced in size until a single 128-bit hash value remains, providing a fixed-size digest of the variable-length input file. The hash function is sensitive to changes in the input, making it suitable for applications like detecting unauthorized file modifications.
This document discusses different frameworks for big data processing at ResearchGate, including Hive, MapReduce, and Flink. It provides an example of using Hive to find the top 5 coauthors for each author based on publication data. Code snippets in Hive SQL and Java are included to implement the top k coauthors user defined aggregate function (UDAF) in Hive. The document evaluates different frameworks based on criteria like features, performance, and usability.
Streaming Data Flow with Apache Flink @ Paris Flink Meetup 2015Till Rohrmann
Apache Flink is an open source platform for distributed stream and batch data processing. It provides APIs called DataStream for unbounded streaming data and DataSet for bounded batch data. Flink runs streaming topologies that allow for windowing, aggregation and other stream processing functions. It supports exactly-once processing semantics through distributed snapshots and checkpoints. The system is optimized for low latency and high throughput streaming applications.
The document discusses various data structures including skip lists, AVL trees, and hashing. It explains that skip lists allow for logarithmic-time operations and are simple to implement. Hashing provides constant-time operations by mapping keys to array indices via a hash function, but collisions must be handled. Common hash functions discussed include summing character codes or converting to a number in a prime base.
An AVL tree, ordered by key insert: a standard insert; (log n) find: a standard find (without removing, of course); (log n) remove: a standard remove; (log n)
Apresentado no TDC Florianópolis - 2016.
Palestra voltada aos que ouviram falar sobre RxJava e querem aprender sobre a biblioteca que todos os programadores legais estão comentando.
program list:
WAP program to show constructor overloading using static member.
WAP to implement multilevel inheritance and method overriding.
WAP to implement interface class and show use of package.
WAP to implement multilevel exception handling and create your own exception.
WAP to implement 3 threads such that 1st sleeps for 200ms, 2nd for 400ms and 3rd for 600ms.
WAP to create applet of moving banner.
WAP to make a simple calculator.
Build a client server chat application.
This document discusses concurrent programming and multithreaded programming in Java. It covers key topics such as creating and controlling threads, thread safety and synchronization, and using bounded queues to allow cooperation between producer and consumer threads.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
1. The document discusses various approaches for writing concurrent and thread-safe code in Java, including using threads, immutable objects, volatile variables, and classes from the java.util.concurrent package.
2. It recommends using high-level concurrency utilities first before lower-level locking, and describes classes like ExecutorService, BlockingQueue, ConcurrentHashMap, and CopyOnWriteArrayList.
3. The document also covers the producer-consumer pattern as an example and introduces the fork/join framework that will be included in JDK 7 for parallelizing recursive tasks.
The document discusses thread synchronization in C# using locks and shared objects. It shows examples of using the "this" keyword, same objects, and different objects to synchronize access to shared data between multiple threads. The examples demonstrate writing data to a list from one thread while reading from another thread, ensuring the threads operate sequentially through locking. Output shows the threads executing in a synchronized, orderly manner when using proper locking and objects.
The document discusses various concepts related to multithreading in Java including thread-safe collections, executors, and synchronizers. It provides details on blocking queues, concurrent hash maps, executors that allow submitting tasks to thread pools, and synchronizers like cyclic barriers, countdown latches, and semaphores that help manage groups of threads. It also discusses how to update Swing components safely from multiple threads using EventQueue methods like invokeLater().
This document provides an introduction to concurrency in Java programming. It discusses modifying a word counting program to run in parallel using threads. It covers thread safety, critical sections, synchronized blocks and methods, lock objects, and other concurrency concepts in Java like volatile fields and deadlocks. The document uses examples to illustrate how to design thread-safe classes and properly synchronize access to shared resources between multiple threads.
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfmail931892
How do I fix it in LinkedList.java?
LabProgram.java
LinkedList.java:
/**
* Defines a doubly-linked list class
* @author
* @author
*/
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
/**
* Instantiates a new LinkedList with default values
* @postcondition
*/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
/**** ACCESSORS ****/
public T getFirst() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
if (iterator != null){
return iterator.data;
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
public void addFirst(T data) {
Node newNode = new Node(data);
if(isEmpty()){
first = newNode;
last = newNode;
}
else{
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if(isEmpty()){
first = newNode;
last = newNode;
}
else{
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
if(iterator != null){
Node newNode = new Node(data);
newNode.next = iterator.next;
iterator.next = newNode;
if (iterator == first){
first = newNode;
}
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/
public void removeFirst() throws NoS.
The document summarizes Software Transactional Memory (STM) and the Multiverse framework. STM provides an alternative to classic locking-based concurrency control using transactions on memory. Multiverse is an STM framework for Java that uses transactions to provide atomic, isolated and consistent access to shared memory without exposing locking details. It supports various programming models including POJO and managed reference based approaches.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
The document discusses code quality analysis tools in Visual Studio 2012, including code analysis, code metrics, code clone analysis, code coverage, and unit testing. It provides examples of code issues found by code analysis tools and how to resolve them, such as fixing spelling errors, removing exceptions, using parameterized queries to prevent SQL injection, and improving code structure and maintainability.
The program defines a jagged array with 3 inner arrays of unspecified length. It initializes the inner arrays. It then iterates through the jagged array and sums all elements of the inner arrays. The total sum is returned.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
The Chain of Responsibility pattern avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. It passes the request along a chain of handlers until one can handle it. This document demonstrates implementing the pattern to handle different calculation requests by passing numbers and operation to linked handler objects that can perform addition, subtraction, multiplication or division.
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
Implement a queue using a linkedlist (java)
Solution
LinkedQueueImplement.java
import java.util.*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedQueue
{
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return front == null;
}
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 :
try
{
System.out.println(\"Peek Element = \"+ lq.peek());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 4 :
System.out.println(\"Empty status = \"+ lq.isEmpty());
break;
case 5 :
System.out.println(\"Size = \"+ lq.getSize());
break;
default :
System.out.println(\"Wrong Entry \ \");
break;
}
/* display queue */
lq.display();
System.out.println(\"\ Do you want to continue (Type y or n) \ \");
ch = scan.next().charAt(0);
} while (ch == \'Y\'|| ch == \'y\');
}
}
Output :
Linked Queue Test
Queue Operations
1. inse.
Adam Sitnik "State of the .NET Performance"Yulia Tsisyk
MSK DOT NET #5
2016-12-07
In this talk Adam will describe how latest changes in.NET are affecting performance.
Adam wants to go through:
C# 7: ref locals and ref returns, ValueTuples.
.NET Core: Spans, Buffers, ValueTasks
And how all of these things help build zero-copy streams aka Channels/Pipelines which are going to be a game changer in the next year.
This document summarizes Adam Sitnik's presentation on .NET performance. It discusses new features in C# 7 like ValueTuple, ref returns and locals, and Span. It also covers .NET Core improvements such as ArrayPool and ValueTask that reduce allocations. The presentation shows how these features improve performance through benchmarks and reduces GC pressure. It provides examples and guidance on best using new features like Span, pipelines, and unsafe code.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
This document provides an overview of arrays in Java, including how to declare, initialize, access, and manipulate array elements. It discusses key array concepts like indexes, the length field, and for loops for traversing arrays. Examples are provided for common array operations like initialization, accessing elements, and passing arrays as parameters or returning them from methods. Limitations of arrays are also covered.
The State Pattern helps organize code that handles multiple states. It defines classes for each state that hold the behavior for that state. The context class maintains a reference to the current state object and forwards requests to it. For an SMTP server example, state classes are defined for idle, initial, transaction started, and data transfer states that each handle commands appropriate for that state and transition to new states. This improves maintainability over approaches with flags and long conditional statements.
The document discusses the Singleton pattern in Java. It describes how a singleton ensures that only one instance of a class exists. It provides examples of implementing a lazy singleton using a static holder class to defer initialization until needed. The document also discusses how depending on static getInstance() calls can make code difficult to test. It proposes using a Supplier interface instead to allow injecting mock dependencies for testing.
More Related Content
Similar to Synchronize access to shared mutable data
program list:
WAP program to show constructor overloading using static member.
WAP to implement multilevel inheritance and method overriding.
WAP to implement interface class and show use of package.
WAP to implement multilevel exception handling and create your own exception.
WAP to implement 3 threads such that 1st sleeps for 200ms, 2nd for 400ms and 3rd for 600ms.
WAP to create applet of moving banner.
WAP to make a simple calculator.
Build a client server chat application.
This document discusses concurrent programming and multithreaded programming in Java. It covers key topics such as creating and controlling threads, thread safety and synchronization, and using bounded queues to allow cooperation between producer and consumer threads.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
1. The document discusses various approaches for writing concurrent and thread-safe code in Java, including using threads, immutable objects, volatile variables, and classes from the java.util.concurrent package.
2. It recommends using high-level concurrency utilities first before lower-level locking, and describes classes like ExecutorService, BlockingQueue, ConcurrentHashMap, and CopyOnWriteArrayList.
3. The document also covers the producer-consumer pattern as an example and introduces the fork/join framework that will be included in JDK 7 for parallelizing recursive tasks.
The document discusses thread synchronization in C# using locks and shared objects. It shows examples of using the "this" keyword, same objects, and different objects to synchronize access to shared data between multiple threads. The examples demonstrate writing data to a list from one thread while reading from another thread, ensuring the threads operate sequentially through locking. Output shows the threads executing in a synchronized, orderly manner when using proper locking and objects.
The document discusses various concepts related to multithreading in Java including thread-safe collections, executors, and synchronizers. It provides details on blocking queues, concurrent hash maps, executors that allow submitting tasks to thread pools, and synchronizers like cyclic barriers, countdown latches, and semaphores that help manage groups of threads. It also discusses how to update Swing components safely from multiple threads using EventQueue methods like invokeLater().
This document provides an introduction to concurrency in Java programming. It discusses modifying a word counting program to run in parallel using threads. It covers thread safety, critical sections, synchronized blocks and methods, lock objects, and other concurrency concepts in Java like volatile fields and deadlocks. The document uses examples to illustrate how to design thread-safe classes and properly synchronize access to shared resources between multiple threads.
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfmail931892
How do I fix it in LinkedList.java?
LabProgram.java
LinkedList.java:
/**
* Defines a doubly-linked list class
* @author
* @author
*/
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
/**
* Instantiates a new LinkedList with default values
* @postcondition
*/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
/**** ACCESSORS ****/
public T getFirst() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()){
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
/**
* Returns the data stored in the iterator node
* @precondition
* @return the data stored in the iterator node
* @throw NullPointerException
*/
public T getIterator() throws NullPointerException {
if (iterator != null){
return iterator.data;
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/**
* Returns the current length of the LinkedList
* @return the length of the LinkedList from 0 to n
*/
public int getLength() {
return length;
}
/**
* Returns whether the LinkedList is currently empty
* @return whether the LinkedList is empty
*/
public boolean isEmpty() {
return length == 0;
}
/**
* Returns whether the iterator is offEnd, i.e. null
* @return whether the iterator is null
*/
public boolean offEnd() {
return iterator == null;
}
/**** MUTATORS ****/
public void addFirst(T data) {
Node newNode = new Node(data);
if(isEmpty()){
first = newNode;
last = newNode;
}
else{
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if(isEmpty()){
first = newNode;
last = newNode;
}
else{
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
/**
* Inserts a new element after the iterator
* @param data the data to insert
* @precondition
* @throws NullPointerException
*/
public void addIterator(T data) throws NullPointerException{
if(iterator != null){
Node newNode = new Node(data);
newNode.next = iterator.next;
iterator.next = newNode;
if (iterator == first){
first = newNode;
}
}else{
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
/
public void removeFirst() throws NoS.
The document summarizes Software Transactional Memory (STM) and the Multiverse framework. STM provides an alternative to classic locking-based concurrency control using transactions on memory. Multiverse is an STM framework for Java that uses transactions to provide atomic, isolated and consistent access to shared memory without exposing locking details. It supports various programming models including POJO and managed reference based approaches.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
The document discusses code quality analysis tools in Visual Studio 2012, including code analysis, code metrics, code clone analysis, code coverage, and unit testing. It provides examples of code issues found by code analysis tools and how to resolve them, such as fixing spelling errors, removing exceptions, using parameterized queries to prevent SQL injection, and improving code structure and maintainability.
The program defines a jagged array with 3 inner arrays of unspecified length. It initializes the inner arrays. It then iterates through the jagged array and sums all elements of the inner arrays. The total sum is returned.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
The Chain of Responsibility pattern avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. It passes the request along a chain of handlers until one can handle it. This document demonstrates implementing the pattern to handle different calculation requests by passing numbers and operation to linked handler objects that can perform addition, subtraction, multiplication or division.
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
Implement a queue using a linkedlist (java)
Solution
LinkedQueueImplement.java
import java.util.*;
class Node
{
protected int data;
protected Node link;
public Node()
{
link = null;
data = 0;
}
public Node(int d,Node n)
{
data = d;
link = n;
}
public void setLink(Node n)
{
link = n;
}
public void setData(int d)
{
data = d;
}
public Node getLink()
{
return link;
}
public int getData()
{
return data;
}
}
class linkedQueue
{
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return front == null;
}
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 :
try
{
System.out.println(\"Peek Element = \"+ lq.peek());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 4 :
System.out.println(\"Empty status = \"+ lq.isEmpty());
break;
case 5 :
System.out.println(\"Size = \"+ lq.getSize());
break;
default :
System.out.println(\"Wrong Entry \ \");
break;
}
/* display queue */
lq.display();
System.out.println(\"\ Do you want to continue (Type y or n) \ \");
ch = scan.next().charAt(0);
} while (ch == \'Y\'|| ch == \'y\');
}
}
Output :
Linked Queue Test
Queue Operations
1. inse.
Adam Sitnik "State of the .NET Performance"Yulia Tsisyk
MSK DOT NET #5
2016-12-07
In this talk Adam will describe how latest changes in.NET are affecting performance.
Adam wants to go through:
C# 7: ref locals and ref returns, ValueTuples.
.NET Core: Spans, Buffers, ValueTasks
And how all of these things help build zero-copy streams aka Channels/Pipelines which are going to be a game changer in the next year.
This document summarizes Adam Sitnik's presentation on .NET performance. It discusses new features in C# 7 like ValueTuple, ref returns and locals, and Span. It also covers .NET Core improvements such as ArrayPool and ValueTask that reduce allocations. The presentation shows how these features improve performance through benchmarks and reduces GC pressure. It provides examples and guidance on best using new features like Span, pipelines, and unsafe code.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
This document provides an overview of arrays in Java, including how to declare, initialize, access, and manipulate array elements. It discusses key array concepts like indexes, the length field, and for loops for traversing arrays. Examples are provided for common array operations like initialization, accessing elements, and passing arrays as parameters or returning them from methods. Limitations of arrays are also covered.
Similar to Synchronize access to shared mutable data (20)
The State Pattern helps organize code that handles multiple states. It defines classes for each state that hold the behavior for that state. The context class maintains a reference to the current state object and forwards requests to it. For an SMTP server example, state classes are defined for idle, initial, transaction started, and data transfer states that each handle commands appropriate for that state and transition to new states. This improves maintainability over approaches with flags and long conditional statements.
The document discusses the Singleton pattern in Java. It describes how a singleton ensures that only one instance of a class exists. It provides examples of implementing a lazy singleton using a static holder class to defer initialization until needed. The document also discusses how depending on static getInstance() calls can make code difficult to test. It proposes using a Supplier interface instead to allow injecting mock dependencies for testing.
Inheritance can make code fragile and inflexible, while composition is more flexible. The document discusses favoring composition over inheritance and provides examples. It shows how inheritance between an Order class and CampaignOrder class can break if Order is refactored. Using composition, different order types implement the same interface without relying on each other's implementations. For beverages, inheritance led to an explosion of subclasses, while composition created reusable wrapper classes. Overall, the document advocates favoring composition over inheritance for increased stability and flexibility.
Wildcards with extends allow flexibility when getting values out of a container by accepting subtypes, while wildcards with super allow flexibility when putting values into a container by accepting supertypes. The Get and Put Principle recommends using extends when only getting values, super when only putting values, and no wildcard when both getting and putting. Key limitations are that extends only allows null to be added and super only allows the Object type to be retrieved.
The document provides tips and examples for using Mockito and AssertJ libraries for unit testing in Java. It describes Mockito annotations like @Mock, @InjectMocks, and @Captor that simplify mocking objects. It shows how to write tests with and without these annotations. It also demonstrates how to make assertions with AssertJ's fluent API for readability and richer assertions compared to JUnit assertions. Examples include testing both happy and unhappy paths as well as capturing arguments with @Captor.
Java EE is a set of API specifications for enterprise application development on the Java platform that focuses on server-side development. It includes APIs like JAX-RS for RESTful web services, JPA for object-relational mapping, and JBatch for batch processing. Java EE applications can be run on various application servers like GlassFish, WildFly, WebSphere, and WebLogic. Java EE offers a rich set of APIs for server-side development that are built and maintained by experts in the community.
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Unveiling the Advantages of Agile Software Development.pdfbrainerhub1
Learn about Agile Software Development's advantages. Simplify your workflow to spur quicker innovation. Jump right in! We have also discussed the advantages.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
When it is all about ERP solutions, companies typically meet their needs with common ERP solutions like SAP, Oracle, and Microsoft Dynamics. These big players have demonstrated that ERP systems can be either simple or highly comprehensive. This remains true today, but there are new factors to consider, including a promising new contender in the market that’s Odoo. This blog compares Odoo ERP with traditional ERP systems and explains why many companies now see Odoo ERP as the best choice.
What are ERP Systems?
An ERP, or Enterprise Resource Planning, system provides your company with valuable information to help you make better decisions and boost your ROI. You should choose an ERP system based on your company’s specific needs. For instance, if you run a manufacturing or retail business, you will need an ERP system that efficiently manages inventory. A consulting firm, on the other hand, would benefit from an ERP system that enhances daily operations. Similarly, eCommerce stores would select an ERP system tailored to their needs.
Because different businesses have different requirements, ERP system functionalities can vary. Among the various ERP systems available, Odoo ERP is considered one of the best in the ERp market with more than 12 million global users today.
Odoo is an open-source ERP system initially designed for small to medium-sized businesses but now suitable for a wide range of companies. Odoo offers a scalable and configurable point-of-sale management solution and allows you to create customised modules for specific industries. Odoo is gaining more popularity because it is built in a way that allows easy customisation, has a user-friendly interface, and is affordable. Here, you will cover the main differences and get to know why Odoo is gaining attention despite the many other ERP systems available in the market.
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
2. An important fact about mutable data and
concurrency in Java
• An update on mutable data made by one thread may not be visible by
other threads unless an appropriate synchronization is used.
• Such unsynchronized shared mutable data can cause nasty problems.
2
3. Example: a thread that never sees an update
3
class ThisNeverFinishesOnMyLaptop {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread backgroundThread = new Thread(() -> {
while (true) { // wait until the counter gets incremented
if (counter.getCount() != 0) break; // this never breaks; it becomes an infinite loop
}
System.out.println("Finished");
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
counter.increment();
}
}
class Counter {
int count = 0; // this is mutable data
int getCount() { return count; }
int increment() { return ++count; }
}
Code based on the example from Effective Java, 3rd edition p.312
4. Synchronization with synchronized blocks
4
class NowItFinishesOnMyLaptop {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Object lock = new Object();
Thread backgroundThread = new Thread(() -> {
while (true) { // wait until the counter gets incremented
synchronized (lock) {
if (counter.getCount() != 0) break; //now it works
}
}
System.out.println("Finished");
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
synchronized (lock) {
counter.increment();
}
}
}
5. Synchronization with volatile
5
class ThisAlsoFinishesOnMyLaptop {
public static void main(String[] args) throws InterruptedException {
VolatileCounter counter = new VolatileCounter();
Thread backgroundThread = new Thread(() -> {
while (true) { // wait until the counter gets incremented
if (counter.getCount() != 0) break; //now it works too
}
System.out.println("Finished");
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
counter.increment();
}
}
class VolatileCounter {
volatile int count = 0;
int getCount() { return count; }
int increment() { return ++count; }
}
6. A limitation of volatile: it doesn’t guarantee
atomicity
6
class IncrementByMultipleThreads {
public static void main(String[] args) {
VolatileCounter counter = new VolatileCounter();
Set<Integer> ints = Collections.synchronizedSet(new HashSet<>());
Runnable incrementer = () -> {
while (true) {
int increment = counter.increment();
boolean added = ints.add(increment);
if (!added) System.out.println("duplicate number detected");//volatile doesn’t prevent this
}
};
Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer);
t1.start(); t2.start(); t3.start();
}
}
7. Synchronization with synchronized blocks
guarantees exclusive code execution
7
class IncrementByMultipleThreadsWithLock {
public static void main(String[] args) {
Counter counter = new Counter();
Object lock = new Object();
Set<Integer> ints = Collections.synchronizedSet(new HashSet<>());
Runnable incrementer = () -> {
while (true) {
int increment;
synchronized (lock) {
increment = counter.increment();
}
boolean added = ints.add(increment);
if (!added) System.out.println("duplicate number detected"); //this doesn’t happen anymore
}
};
Thread t1 = new Thread(incrementer), t2 = new Thread(incrementer), t3 = new Thread(incrementer);
t1.start(); t2.start(); t3.start();
}
}
8. Which classes in JDK need a synchronization
in concurrent use cases?
• HashMap
• It can trigger an infinite loop in some cases, which is extremely dangerous.
• https://mailinator.blogspot.com/2009/06/beautiful-race-condition.html
• Thread-safe equivalent: ConcurrentHashMap
• ArrayList
• Thread-safe equivalent: CopyOnWriteArrayList
• SimpleDateFormat
• Oftentimes it’s stored in a public static final field; dangerous
• Thread-safe equivalent: DateTimeFormatter
• DecimalFormat, MessageFormat, etc.
• Many more
8
Note: Just putting volatile doesn’t make those classes thread-safe.
9. Conclusion
• We have discussed:
• Why we need to synchronize shared mutable data
• How we can do that
• What happens when we fail to do that
• The consequences of missing synchronization can be horrible:
• Triggering an infinite loop
• Getting an invalid result or a mysterious exception
• Any sort of totally unpredictable chaos
• Minimize mutability. Immutable data is always thread-safe.
• Further reading: Java Concurrency in Practice
9