public class ProducerConsumerProblem {
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
List<Integer> buffer = new LinkedList<>();
Condition isEmpty = lock.newCondition();
Condition isFull = lock.newCondition();
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Callable<String>> list = new ArrayList<>();
list.add(new Producer(lock, buffer, isEmpty, isFull));
list.add(new Consumer(lock, buffer, isEmpty, isFull));
final List<Future<String>> futures = executorService.invokeAll(list);
futures.forEach(stringFuture -> {
try {
System.out.println("Done :" + stringFuture.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
System.out.println("ExecutorService Shutdown");
}
});
}
private static class Producer implements Callable<String> {
private Lock producerLock;
private List<Integer> buffer;
Condition isEmpty;
Condition isFull;
Producer(Lock lock, List<Integer> buffer, Condition isEmpty, Condition isFull) {
this.producerLock = lock;
this.buffer = buffer;
this.isEmpty = isEmpty;
this.isFull = isFull;
}
@Override
public String call() throws Exception {
int count = 1;
for (; count <= 50; count++) {
try {
producerLock.lock();
if (buffer.size() == 50) {
isFull.await();
}
buffer.add(1);
isEmpty.signalAll();
} finally {
producerLock.unlock();
}
}
return "Produced : " + (count - 1);
}
}
private static class Consumer implements Callable<String> {
private Lock consumerLock;
private List<Integer> buffer;
Condition isEmpty;
Condition isFull;
Consumer(Lock lock, List<Integer> buffer, Condition isEmpty, Condition isFull) {
this.consumerLock = lock;
this.buffer = buffer;
this.isEmpty = isEmpty;
this.isFull = isFull;
}
@Override
public String call() throws Exception {
int count = 1;
for (; count <= 50; count++) {
try {
consumerLock.lock();
if (buffer.isEmpty()) {
isEmpty.await();
}
buffer.remove(buffer.size() - 1);
isFull.signalAll();
} finally {
consumerLock.unlock();
}
}
return "Consumed : " + (count - 1);
}
}
}
Producer Consumer Problem Reentrant Lock
Include conditional dependencies and packages in gradle
I got a task in my project to add some dependencies on need basis.
We are creating a jar for different tools, lots of code we have common but some of code and dependencies required for jar is not needed for other.
Before directly jumping into actual code base I wanted get my hand dirty in some dummy project, So I have spent some time to understands gradle tasks and dependency management and created the dummy project.
I am rewriting here for my own benefit and yours as well.
We can add dependencies by providing build time argument
To add the conditional dependency we need to run our build command
We can create the separate task for separate Jars.
Task build the Jar for Build1:-
We are creating a jar for different tools, lots of code we have common but some of code and dependencies required for jar is not needed for other.
Before directly jumping into actual code base I wanted get my hand dirty in some dummy project, So I have spent some time to understands gradle tasks and dependency management and created the dummy project.
I am rewriting here for my own benefit and yours as well.
We can add dependencies by providing build time argument
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
if(project.property("build").equals("build1")){
println "Including dependencies of build1"
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
}
if (project.property("build").equals("build2")){
println "Including dependencies of build2"
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
}
}
testCompile group: 'junit', name: 'junit', version: '4.12'
if(project.property("build").equals("build1")){
println "Including dependencies of build1"
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
}
if (project.property("build").equals("build2")){
println "Including dependencies of build2"
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
}
}
To add the conditional dependency we need to run our build command
gradle build -Pbuild="build1"
Or
gradle build -Pbuild="build2"
Or
gradle build -Pbuild="build2"
We can create the separate task for separate Jars.
Task build the Jar for Build1:-
task build1Jar(type: Jar){
from sourceSets.main.output
exclude '**/package2/**'
manifest {
attributes(
"Manifest-Version": "1.0",
"Main-Class" : "com.ravat.package1.Runner",
"Class-Path": configurations.runtimeClasspath.collect { it.getName() }.join(' ')
)
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
baseName = 'build1'
}
Task build the Jar for Build2:-from sourceSets.main.output
exclude '**/package2/**'
manifest {
attributes(
"Manifest-Version": "1.0",
"Main-Class" : "com.ravat.package1.Runner",
"Class-Path": configurations.runtimeClasspath.collect { it.getName() }.join(' ')
)
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
baseName = 'build1'
}
task build2Jar(type: Jar){
from sourceSets.main.output
exclude '**/package1/**'
manifest {
attributes(
"Manifest-Version": "1.0",
"Main-Class" : "com.ravat.package2.Runner",
"Class-Path": configurations.runtimeClasspath.collect { it.getName() }.join(' ')
)
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
baseName = 'build2'
}
To create a jar with required dependencies and package we need to run the following gradle commandfrom sourceSets.main.output
exclude '**/package1/**'
manifest {
attributes(
"Manifest-Version": "1.0",
"Main-Class" : "com.ravat.package2.Runner",
"Class-Path": configurations.runtimeClasspath.collect { it.getName() }.join(' ')
)
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
baseName = 'build2'
}
gradle clean install build1Jar
or
gradle clean install build2Jar
or
gradle clean install build2Jar
Magic of bit manipulation : fastest way to swap two variables
We all have faced this question in our interview process to swap 2 variables.
If not faces while working with arrays we may have faced to swap 2 variables in array.
I hope, you all know the concept of swapping 2 variables. today I am going to show you the fastest way to swap two variables.
We all know data is stored in computer memory in the form of bits(0 & 1), that means all the operation we do on the bits will be perform faster by computer.
some bit manipulation examples :-
We will use XOR Operator to swap 2 variable :-
If not faces while working with arrays we may have faced to swap 2 variables in array.
I hope, you all know the concept of swapping 2 variables. today I am going to show you the fastest way to swap two variables.
We all know data is stored in computer memory in the form of bits(0 & 1), that means all the operation we do on the bits will be perform faster by computer.
some bit manipulation examples :-
Bitwise XOR operator :-
value ^ 0s == value
value ^ 1s == ~value
value ^ value == 0s
Bitwise AND Operator :-
value & 0s == 0s
value & 1s == value
value & value == value
Bitwise OR Operator :-
value | 0s == value
value | 1s == 1s
value | value == value
value ^ 0s == value
value ^ 1s == ~value
value ^ value == 0s
Bitwise AND Operator :-
value & 0s == 0s
value & 1s == value
value & value == value
Bitwise OR Operator :-
value | 0s == value
value | 1s == 1s
value | value == value
We will use XOR Operator to swap 2 variable :-
x = 10
y = 12
8 4 2 1
1 0 1 0 = 10(x)
1 1 0 0 = 12(y)
x = x ^ y 1010^1100 = 0110
y = x ^ y 0110^1100 = 1010 (10)
x = x ^ y 0110^1010 = 1100 (12)
We will implement a bubble sort algorithm to see the benefit of bit manipulation:-y = 12
8 4 2 1
1 0 1 0 = 10(x)
1 1 0 0 = 12(y)
x = x ^ y 1010^1100 = 0110
y = x ^ y 0110^1100 = 1010 (10)
x = x ^ y 0110^1010 = 1100 (12)
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] array = new int[]{20,35,-15,7,55,1,-22};
array = bubbleSort(array);
System.out.println(Arrays.toString(array));
}
private static int[] bubbleSort(int[] array) {
for (int i=0;i<array.length;i++){
for (int j=0;j < array.length-i-1;j++) {
if (array[j] > array[j+1]){
//fastest way to swap two variable
array[j] = array[j] ^ array[j+1];
array[j+1] = array[j] ^ array [j+1];
array[j] = array[j] ^array[j+1];
}
}
}
return array;
}
}
How can use HashSet to solve Array related Problems
Today I was solving some array related problems on GeeksForGeeks,
Came across with solution How Hashset helped me to solve these problems for large amount of input within given time complexity.
Here is the problem statements I have solved:-
Problem Statement:- Pair with given sum in a sorted array
Solution :-
Problem Statement:- Triplet Sum in Array
Solution :-
Came across with solution How Hashset helped me to solve these problems for large amount of input within given time complexity.
Here is the problem statements I have solved:-
Problem Statement:- Pair with given sum in a sorted array
Solution :-
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T --> 0){
int N = Integer.parseInt(br.readLine());
String str = br.readLine();
String[] inputArr = str.trim().split("\\s+");
int A[] = new int[N];
for(int i=0;i<N;i++){
A[i] = Integer.parseInt(inputArr[i]);
}
int K = Integer.parseInt(br.readLine());
int low = 0;
int high = N-1;
boolean flag = true;
while(low<high){
if(A[low]+A[high] > K){
high--;
}else if(A[low]+A[high] < K){
low++;
}else{
System.out.println(A[low]+" "+A[high] + " "+ K);
low++;
flag = false;
}
}
if(flag){
System.out.println(-1);
}
}
}
}
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T --> 0){
int N = Integer.parseInt(br.readLine());
String str = br.readLine();
String[] inputArr = str.trim().split("\\s+");
int A[] = new int[N];
for(int i=0;i<N;i++){
A[i] = Integer.parseInt(inputArr[i]);
}
int K = Integer.parseInt(br.readLine());
int low = 0;
int high = N-1;
boolean flag = true;
while(low<high){
if(A[low]+A[high] > K){
high--;
}else if(A[low]+A[high] < K){
low++;
}else{
System.out.println(A[low]+" "+A[high] + " "+ K);
low++;
flag = false;
}
}
if(flag){
System.out.println(-1);
}
}
}
}
Problem Statement:- Triplet Sum in Array
Solution :-
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T --> 0){
String input = br.readLine();
String[] inputArry = input.trim().split("\\s+");
int N = Integer.parseInt(inputArry[0]);
int X = Integer.parseInt(inputArry[1]);
String arrInp = br.readLine();
String[] arr = arrInp.trim().split("\\s+");
int[] A = new int[N];
for(int i=0;i<N;i++){
A[i] = Integer.parseInt(arr[i]);
}
Set<Integer> sumSet = new HashSet<>();
boolean flag= true;
for(int i=0;i<N;i++){
if(sumSet.contains(X-A[i])){
System.out.println("1");
flag = false;
break;
}else{
for(int j=0;j<=i;j++){
sumSet.add(A[i]+A[j]);
}
}
}
if(flag){
System.out.println("0");
}
}
}
}
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T --> 0){
String input = br.readLine();
String[] inputArry = input.trim().split("\\s+");
int N = Integer.parseInt(inputArry[0]);
int X = Integer.parseInt(inputArry[1]);
String arrInp = br.readLine();
String[] arr = arrInp.trim().split("\\s+");
int[] A = new int[N];
for(int i=0;i<N;i++){
A[i] = Integer.parseInt(arr[i]);
}
Set<Integer> sumSet = new HashSet<>();
boolean flag= true;
for(int i=0;i<N;i++){
if(sumSet.contains(X-A[i])){
System.out.println("1");
flag = false;
break;
}else{
for(int j=0;j<=i;j++){
sumSet.add(A[i]+A[j]);
}
}
}
if(flag){
System.out.println("0");
}
}
}
}
First non repeating word in string.
public String firstNonRepeatingword(String string) {
if(string == null || string.isEmpty()) {
return "No unique word found";
}else {
StringTokenizer tokens = new StringTokenizer(string);
LinkedList<String> list = new LinkedList<>();
while(tokens.hasMoreTokens()) {
list.add(tokens.nextToken());
}
for(int i=0;i<list.size();i++) {
if (Collections.frequency(list,list.get(i)) == 1) {
return list.get(i);
}
}
}
return "No unique word found";
}
if(string == null || string.isEmpty()) {
return "No unique word found";
}else {
StringTokenizer tokens = new StringTokenizer(string);
LinkedList<String> list = new LinkedList<>();
while(tokens.hasMoreTokens()) {
list.add(tokens.nextToken());
}
for(int i=0;i<list.size();i++) {
if (Collections.frequency(list,list.get(i)) == 1) {
return list.get(i);
}
}
}
return "No unique word found";
}
It's up to you how are you spliting the string there are many ways, If you have small string tokenizer is fast.
Performance of StringTokenizer class vs. String.split method vs indexOf
Subscribe to:
Posts (Atom)
Functional programming with Java - Part 1
Recently I was reviewing one PR raised by team memeber and going through one utitlity method and found out there are too many muatable vari...
-
Recently I was reviewing one PR raised by team memeber and going through one utitlity method and found out there are too many muatable vari...
-
It creates an anonymous class derived from the specified class (the outer braces), and provide an initializer block within that class (the...
-
I got a task in my project to add some dependencies on need basis. We are creating a jar for different tools, lots of code we have common...