Demo 2. Example of a simple multi thread Builder - aegisql/conveyor GitHub Wiki
ThreadPool - Helping multi-thread executor
Take Demo 1 example and place it into a mini-thread environment.
/*
* COPYRIGHT (C) AEGIS DATA SOLUTIONS, LLC, 2015
*/
package com.aegisql.conveyor.demo.simple_builder;
import java.util.Date;
public class Person {
final String firstName;
final String lastName;
final Date dateOfBirth;
public Person(String firstName, String lastName, Date dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", dateOfBirth=" + dateOfBirth + "]";
}
}
/*
* COPYRIGHT (C) AEGIS DATA SOLUTIONS, LLC, 2015
*/
package com.aegisql.conveyor.demo.simple_builder_asynch;
import java.util.Date;
import java.util.function.Supplier;
public class PersonBuilder implements Supplier<Person> {
private String firstName;
private String lastName;
private Date dateOfBirth;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public Person get() {
return new Person(firstName,lastName,dateOfBirth);
}
}
ThreadPool pool = new ThreadPool();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
PersonBuilder builder = new PersonBuilder();
// << Builder is created, but it is empty.
// Needs three pieces of data to build the person
// Adding building parts asynchronously in three separate threads
Future<?> f1 = pool.runAsynchWithDelay(10,()->{
builder.setFirstName("John");
}
);
Future<?> f2 = pool.runAsynchWithDelay(100,()->{
builder.setLastName("Silver");
}
);
Future<?> f3 = pool.runAsynchWithDelay(1000,()->{
try {
builder.setDateOfBirth( format.parse("1695-11-10") );
} catch (Exception e) {}
}
);
// Most likely not ready
Person person = builder.get();
System.out.println( "0\t"+ person );
f1.get();
// not ready
person = builder.get();
System.out.println( "10\t"+ person );
f2.get();
// still not ready
person = builder.get();
System.out.println( "100\t"+ person );
f3.get();
// Hopefully ready now
person = builder.get();
System.out.println( "1000\t"+ person );
pool.shutdown();
0 Person [firstName=null, lastName=null, dateOfBirth=null]
10 Person [firstName=John, lastName=null, dateOfBirth=null]
100 Person [firstName=John, lastName=Silver, dateOfBirth=null]
1000 Person [firstName=John, lastName=Silver, dateOfBirth=Thu Nov 10 00:00:00 EST 1695]