Wednesday, December 14, 2016

Task execution in different ways with Java

Task execution in different ways


public class ExecuteTask {
public static void main(String[] args) {
// Runs in the main thread
helloWorld();
// Runs in a new thread
new Thread(ExecuteTask::helloWorld).start();
// Runs in the default fork join pool
ForkJoinPool.commonPool().submit(ExecuteTask::helloWorld);
// Runs in the default fork join pool via a CompletableFuture
CompletableFuture.runAsync(ExecuteTask::helloWorld);
// Runs in a custom fork join pool (with three workers)
new ForkJoinPool(3).submit(ExecuteTask::helloWorld);
// Queues up task in a single thread executor
Executors.newSingleThreadExecutor().execute(ExecuteTask::helloWorld);
// Caches tasks so that short lived re-occurring tasks can execute faster
Executors.newCachedThreadPool().execute(ExecuteTask::helloWorld);
// Runs in a separate thread pool with the given delay
Executors.newScheduledThreadPool(2).schedule(ExecuteTask::helloWorld, 10, TimeUnit.MILLISECONDS);
}
public static void helloWorld() {
System.out.println("Hello World greeting from " + Thread.currentThread().getName());
}
}

Wednesday, November 30, 2016

Java 8 Parallel Stream Basic Usage & Perf. Test

public class Main {
public static void main (String[] args) {
Stomach stomach = new Stomach ();
long startTime = System.currentTimeMillis ();
for (int i = 0; i < 10000; i++) {
stomach.accept (new Salad ());
stomach.accept (new Burger ());
}
long normalDigestionDuration = System.currentTimeMillis () - startTime;
//------------------------------------------------------------------------------------------
Consumer<Food> c = (Food food)-> {
System.out.println ("Eating the " +food);
};
List<Food> foods = new ArrayList<> ();
for (int i = 0; i < 10000; i++) {
stomach.accept (new Salad ());
stomach.accept (new Burger ());
}
startTime = System.currentTimeMillis ();
foods.parallelStream ().map (food->{consumeFood (food,c);return food;}).count ();
long paralelStreamDigestDuration = System.currentTimeMillis () - startTime;
//------------------------------------------------------------------------------------------
System.out.println ("Digestion duration is :" + normalDigestionDuration);// ~120 ms
System.out.println ("Digestion with parallel stream = " + paralelStreamDigestDuration);// ~7 ms...so fast huh ?
}
public static void consumeFood (Food food, Consumer<Food> consumer){
consumer.accept (food);
}
}
Outputs::
Digestion duration is :120
Digestion with parallel stream = 7

Tuesday, November 29, 2016

Java 8 Consumer SAM sample

public abstract class Food {
public abstract void giveEnergy () ;
}
public class Burger extends Food {
@Override
public void giveEnergy () {
System.out.println ("Burger gives high energy");
}
}
public class Salad extends Food {
@Override
public void giveEnergy () {
System.out.println ("Salad does not give energy");
}
}
package com.company.samples.way6;
import java.util.function.Consumer;
public class Stomach<T extends Food> implements Consumer<T> {
@Override
public void accept (T t) {
t.giveEnergy ();
}
}
package com.company.samples.way6;
public class Main {
public static void main (String[] args) {
Stomach stomach = new Stomach ();
stomach.accept (new Salad ());
stomach.accept (new Burger ());
}
}
Outputs:::
Salad does not give energy
Burger gives high energy

Java 8 stream samples not much but easily reachable


package com.company.samples.way4;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by serkan on 28.11.2016.
*/
public class Main {
public static void main (String[] args) {
List<Person> roster = new ArrayList<Person> ();
roster.add (new Person ("John", 23, Gender.Male));
roster.add (new Person ("wayne", 37, Gender.Male));
roster.add (new Person ("Angelina", 23, Gender.Femal));
roster.add (new Person ("Jolie", 12, Gender.Femal));
roster.add (new Person ("Wolverine", 500, Gender.Male));
roster.add (new Person ("Xavier", 70, Gender.Male));
roster.add (new Person ("Aişe", 6, Gender.Femal));
roster.add (new Person ("Aişe", 6, Gender.Femal));
Map<Gender, List<Person>> byGender = roster.parallelStream ().collect (Collectors.groupingByConcurrent (Person::getGender));
System.out.println ("byGender = " + byGender);//this is so cool huh ?
Double averageAge = roster.parallelStream ().collect (Collectors.averagingInt (Person::getAge));
System.out.println ("averageAge = " + averageAge);
OptionalDouble anotherAverageAge = roster.parallelStream ().mapToInt (p -> p.getAge ()).average ();
System.out.println ("anotherAverageAge = " + anotherAverageAge);
List<Person> femalesOnly = roster.parallelStream ().filter (p -> p.getGender () == Gender.Femal).collect (Collectors.toList ());
System.out.println ("femalesOnly = " + femalesOnly);
List<Person> distinct = roster.parallelStream ().distinct ().collect (Collectors.toList ());
System.out.println ("distinct = " + distinct);
Set<Person> anotherDistinct = roster.parallelStream ().collect (Collectors.toSet ());
System.out.println ("anotherDistinct = " + anotherDistinct);
int sumOfAges = roster.parallelStream ().mapToInt (Person::getAge).sum ();
System.out.println ("sumOfAges = " + sumOfAges);
int anotherSumOfAges = roster.parallelStream ().mapToInt (p-> p.getAge ()).sum ();
System.out.println ("anotherSumOfAges = " + anotherSumOfAges);
long justAnotherSumOfAges = roster.parallelStream ().collect (Collectors.summarizingInt (Person::getAge)).getSum ();
System.out.println ("justAnotherSumOfAges = " + justAnotherSumOfAges);
final Comparator<Person> comp = (p1, p2) -> Integer.compare( p1.getAge(), p2.getAge());
Person oldest = roster.stream().max(comp).get();
System.out.println ("oldest = " + oldest);
Person youngest = roster.stream().min((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())).get();
System.out.println ("youngest = " + youngest);
String lexicalLatests = roster.parallelStream ().max ((p1, p2) -> p1.getName ().compareTo (p2.getName ())).get ().getName ();
System.out.println ("lexicalLatests = " + lexicalLatests);
}
}
byGender = {Male=[Person{name='Xavier', age=70, gender=Male}, Person{name='Wolverine', age=500, gender=Male}, Person{name='wayne', age=37, gender=Male}, Person{name='John', age=23, gender=Male}], Femal=[Person{name='Aişe', age=6, gender=Femal}, Person{name='Aişe', age=6, gender=Femal}, Person{name='Angelina', age=23, gender=Femal}, Person{name='Jolie', age=12, gender=Femal}]}
averageAge = 84.625
anotherAverageAge = OptionalDouble[84.625]
femalesOnly = [Person{name='Angelina', age=23, gender=Femal}, Person{name='Jolie', age=12, gender=Femal}, Person{name='Aişe', age=6, gender=Femal}, Person{name='Aişe', age=6, gender=Femal}]
distinct = [Person{name='John', age=23, gender=Male}, Person{name='wayne', age=37, gender=Male}, Person{name='Angelina', age=23, gender=Femal}, Person{name='Jolie', age=12, gender=Femal}, Person{name='Wolverine', age=500, gender=Male}, Person{name='Xavier', age=70, gender=Male}, Person{name='Aişe', age=6, gender=Femal}]
anotherDistinct = [Person{name='John', age=23, gender=Male}, Person{name='wayne', age=37, gender=Male}, Person{name='Wolverine', age=500, gender=Male}, Person{name='Xavier', age=70, gender=Male}, Person{name='Angelina', age=23, gender=Femal}, Person{name='Jolie', age=12, gender=Femal}, Person{name='Aişe', age=6, gender=Femal}]
sumOfAges = 677
anotherSumOfAges = 677
justAnotherSumOfAges = 677
oldest = Person{name='Wolverine', age=500, gender=Male}
youngest = Person{name='Aişe', age=6, gender=Femal}
lexicalLatests = wayne

Wednesday, September 7, 2016

Generate FlameGraph for your java projects

1) Clone the lightweight-java-profiler: git clone https://github.com/dcapwell/lightweight-java-profiler.git

2) Go to it : cd lightweight-java-profiler/

3) Compile it: make all

4) Add this to the VM Options : -agentpath:/space/projects/lightweight-java-profiler/build-64/liblagent.so


5) Click Ok..Start the process...Send some requests.. close/terminate the application...traces.txt will be produced after terminating the project..See the below picture ..It is there..At the bottom..That file contains all cpu- measurements about the requests that you have sent (Actually not only the requests, everthing is recorded from the beginning of the time).


Now we need something to display this data..

It is the FlameGraph : https://github.com/brendangregg/FlameGraph

6) Get the FlameGraph : git clone https://github.com/brendangregg/FlameGraph.git

7) Execute the following command under the FlameGraph directory $: ./stackcollapse-ljp.awk < /pathToThe_traces_file/traces.txt | ./flamegraph.pl > traces.svg

8) Open the travces.svg with firefox

firefox travces.svg

9) Press Enter

10) bye




Thursday, September 1, 2016

intellij show spring beans near line number

File > Project Structure > Facets >  Click the green + icon in the middle Panel > Select Spring


After Applying You will be seeing the Bean Definition Pointers as shown below


Wednesday, August 24, 2016

java CompletableFuture example




package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Created by sunels on 21.07.2016.
*/
public class Test03toList {
public static void main (String[] args) {
Test03toList s = new Test03toList ();
List<CompletableFuture<String>> futures = new ArrayList<> ();
CompletableFuture<String> to = CompletableFuture.supplyAsync (s::findReceiver);
futures.add (to);
CompletableFuture<String> text = CompletableFuture.supplyAsync (s::createContent);
futures.add (text);
CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf (futures.toArray (new CompletableFuture[futures.size ()]));
allDoneFuture.join ();
System.out.println ("to:" + getCompletionResultOf (to) + ", text:" + getCompletionResultOf (text));
}
private static String getCompletionResultOf (CompletableFuture<String> to) {
String result = null;
try {
result = to.get ();
} catch (InterruptedException e) {
e.printStackTrace ();
} catch (ExecutionException e) {
e.printStackTrace ();
}
return result;
}
public String findReceiver () {
zleep (2000l);
return "054212312313";
}
public String createContent () {
zleep (4000l);
return "Sn.serkan sunel faturani ödemedin";
}
private void zleep (long dur) {
try {
Thread.currentThread ().sleep (dur);
} catch (InterruptedException e) {
}
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Created by sunels on 21.07.2016.
*/
public class Test03toList {
public static void main (String[] args) {
Test03toList s = new Test03toList ();
List<CompletableFuture<String>> futures = new ArrayList<> ();
CompletableFuture<String> to = CompletableFuture.supplyAsync (s::findReceiver);
futures.add (to);
CompletableFuture<String> text = CompletableFuture.supplyAsync (s::createContent);
futures.add (text);
try {
long start1= System.currentTimeMillis ();
String result1 = to.get ();
System.out.println ("Duration -1:" + (System.currentTimeMillis () - start1));
} catch (InterruptedException e) {
e.printStackTrace ();
} catch (ExecutionException e) {
e.printStackTrace ();
}
try {
long start2= System.currentTimeMillis ();
String result2 = text.get ();
System.out.println ("Duration -2:" + (System.currentTimeMillis () - start2));
} catch (InterruptedException e) {
e.printStackTrace ();
} catch (ExecutionException e) {
e.printStackTrace ();
}
System.out.println ("-- !");
}
private <U> U collectAllresponsesAndFinalizeThem (Void aVoid) {
System.out.println (" Things seems like to be done ! ");
return null;
}
private static String getCompletionResultOf (CompletableFuture<String> to) {
String result = null;
try {
result = to.get ();
} catch (InterruptedException e) {
e.printStackTrace ();
} catch (ExecutionException e) {
e.printStackTrace ();
}
return result;
}
public String findReceiver () {
zleep (14000l);
return "054212312313";
}
public String createContent () {
zleep (24000l);
return "Sn.serkan sunel faturani ödemedin";
}
private void zleep (long dur) {
try {
Thread.currentThread ().sleep (dur);
} catch (InterruptedException e) {
}
}
}
view raw gistfile1.txt hosted with ❤ by GitHub



Saturday, March 19, 2016

Unix sniff network traffic on specific port with tcpflow

Install it : sudo apt-get install tcpflow
Run the command on console : sudo tcpflow -i any -C -J port 1234


sunels@sunels:~$ sudo tcpflow -i any -C -J port 8888
tcpflow: listening on any




GET /hi?name=serkan, HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/48.0.2564.116 Chrome/48.0.2564.116 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8


HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Content-Length: 18
Date: Sat, 19 Mar 2016 20:22:39 GMT


Hi there, serkan,!