multi threading in java with for loop - multithreading

there is an list of student entity.
List<Student> student = new Arraylist<Student>();
where
public student{
private id;
private name;
private class;
//setter and getter
}
By the foreach loop:
for(Student std : student){
System.out.println(std.getName());
}
above is the normal way. But how to print them with multithreading?
three student details together print. means taking three threads toghter

This doesn't serve any practical purpose.
for(Student std:student){
new Thread(()->{
System.out.println(std.getName);
System.out.println(std.getName);
}).start();
}
This is also worse than the answer above.

A simple solution:
studentList.parallelStream().forEach(System.out::println);
This turns your list into a stream, and for each element in that stream, System.out.println() is invoked.
The non-stream solution is of course much more complicated. It would required you to define multiple threads, including a "pattern" how these threads work on that shared list.
For doing it with "raw threads": that is simply, straight forward stuff: you have to "slice" your data into buckets, and then define threads that work different buckets. See here as starting point.

Related

Running methods on different threads

simply put for a hw problem I need to run a bubble sort with 3 million elements. Do this normally. and then sort 4 individual lists (not nearly accurate but is all thats required) of 750000 elements each on a different thread.
I have a class that extends thread that simply prints a line if im running the thread. But I'm not sure how to get it to run a method
class thread extends Thread{
override def run()
{
// Displaying the thread that is running
println("Thread " + Thread.currentThread().getName() +" is running.")
}
}
//this for loop is in an object
for (c <- 1 to 5)
{
var th = new thread()
th.setName(c.toString())
th.start()
}
I am going to stick to answering the question you asked instead of trying to do your homework for you. I hope that is enough to get your started trying things out for yourself.
Recall that class names should be capitalized. That is probably a good thing to remember as your instructor will probably mark you down if you forget that during an exam.
class MyThread extends Thread{
override def run() = {
// Displaying the thread that is running
println("Thread " + Thread.currentThread().getName() +" is running.")
sort()
}
def sort() = {
// my sorting code here
}
}
If your instructor has not restricted you to using Thread only, I would also, similar to Luis Miguel Mejía Suárez, recommend Future instead of Thread. The syntax it uses is cleaner and preferable for how I would do multithreading in a professional setting. However, the choice may not be yours, so if your teacher says use Thread, use Thread.
For a primer on using Futures, see here.
Good luck!

UML class diagram dependency or association

I'm not really sure about how to distinguish whether I should define a relationship as dependency or association for certain cases.
For example,
class AttendanceSheet {
Map<String> students;
boolean[] attend;
public void addStudent(Student s)
{
students.add(s.getName(),s.getStudentNumber());
}
public void checkAttendance(String name) { //... }
}
class Student {
private String name;
private int staffNumber;
//more information such as address, age, etc..
Student(String n, int sn)
{
name = n;
studentNumber = sn;
}
public String getName()
{
return name.clone();
}
public String getStudentNumber()
{
return studentNumber;
}
}
For this case, would Student and Association have association or dependency?
This is because I'm not sure whether the association must have the actual reference of the object or it suffice to just have certain information that can reach the object (since student id and number is far more enough to know find out which student object it is directing to).
In your case the <<uses>> is sufficient, because you don't have actual properties of type Student in AttendanceSheet.
As a side note: not using object references and instead just having the studentNumber is - to say the least - an odd design. But I don't know the context.
On the business level those objects are related, but there is no single preferred method of diagramming this relationship.
Please see Section 9.5.4 of UML specification for more details on the topic, especially Figure 9.12
To be specific those two notations are semantically equivalent (I'm ignoring irrelevant details):
In the first one to keep a traceability you can use an explicit Dependency pretty much the way you did.
One can also consider students as a Shared Aggregation, however it might be also considered an overkill. Not necessary, just showing a possibility for an answer completeness.
You may also consider Qulified associations to indicate a reference to the Student is based on their specific properties. This is pretty much closest to your need. Sorry, I don't know how to achieve such notation in my tool, but you can find more details in Figure 11.37 in Section 11.5 of the aforementioned specification.

Ways to return a list of tuple rows through JPA while using PrimeFaces LazyDataModel<T>

There may be situations where we need to return a list of tuple rows from the associated data model i.e not a fully qualified entity but a part of it, specifically a list of selected columns from the associated data-source (may be a database).
I know of some of ways to return a list of tuple rows from the database using JPA like the following
There is no need to look closely into the code from the JPA criteria API, if you were to dislike criteria queries. The question is not directly related to JPA criteria. I prefer JPA criteria to JPQL for no precise reason - just because I like criteria queries very much.
Using a list of object arrays - List<Object[]> :
public List<Object[]> object(int first, int pageSize) {
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]>criteriaQuery=criteriaBuilder.createQuery(Object[].class);
Root<Product> root = criteriaQuery.from(entityManager.getMetamodel().entity(Product.class));
List<Selection<?>>selections=new ArrayList<Selection<?>>();
selections.add(root.get(Product_.prodId));
selections.add(root.get(Product_.prodName));
selections.add(root.get(Product_.prodCode));
selections.add(root.get(Product_.prodDesc));
selections.add(root.get(Product_.marketPrice));
selections.add(root.get(Product_.salePrice));
criteriaQuery.select(criteriaBuilder.array(selections.toArray(new Selection[0])));
//Or criteriaQuery.multiselect(selections.toArray(new Selection[0]));
return entityManager.createQuery(criteriaQuery).setFirstResult(first).setMaxResults(pageSize).getResultList();
}
Using a list of tuples - List<Tuple> :
public List<Tuple> tuple(int first, int pageSize) {
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple>criteriaQuery=criteriaBuilder.createTupleQuery();
Root<Product> root = criteriaQuery.from(entityManager.getMetamodel().entity(Product.class));
List<Selection<?>>selections=new ArrayList<Selection<?>>();
selections.add(root.get(Product_.prodId));
selections.add(root.get(Product_.prodName));
selections.add(root.get(Product_.prodCode));
selections.add(root.get(Product_.prodDesc));
selections.add(root.get(Product_.marketPrice));
selections.add(root.get(Product_.salePrice));
criteriaQuery.select(criteriaBuilder.tuple(selections.toArray(new Selection[0])));
//Or criteriaQuery.multiselect(selections.toArray(new Selection[0]));
return entityManager.createQuery(criteriaQuery).setFirstResult(first).setMaxResults(pageSize).getResultList();
}
Using a list of rows mapped a class of objects - List<MappedClass> :
public List<ProductUtils> constructor(int first, int pageSize) {
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<ProductUtils>criteriaQuery=criteriaBuilder.createQuery(ProductUtils.class);
Root<Product> root = criteriaQuery.from(entityManager.getMetamodel().entity(Product.class));
List<Selection<?>>selections=new ArrayList<Selection<?>>();
selections.add(root.get(Product_.prodId));
selections.add(root.get(Product_.prodName));
selections.add(root.get(Product_.prodCode));
selections.add(root.get(Product_.prodDesc));
selections.add(root.get(Product_.marketPrice));
selections.add(root.get(Product_.salePrice));
criteriaQuery.select(criteriaBuilder.construct(ProductUtils.class, selections.toArray(new Selection[0])));
//Or criteriaQuery.multiselect(selections.toArray(new Selection[0]));
return entityManager.createQuery(criteriaQuery).setFirstResult(first).setMaxResults(pageSize).getResultList();
}
Again the same thing can be rewritten using JPQL.
The first two of them are ugly and require accessing properties using indices in EL on XHTML pages. Maintaining them is difficult, if the order in which the fields appear is changed at a later time (of course, aliases can be used with Tuple). Also, use of Tuple is always avoidable, since it requires an additional dependency in JSF from the javax.persistence package increasing coupling between modules.
Using a constructor query to map the result list to a class may suffice. It can be used along with PrimeFaces LazyDataModel as follows.
#Named
#ViewScoped
public class TestManagedBean extends LazyDataModel<ProductUtils> implements Serializable {
#Inject
private Service service;
private static final long serialVersionUID=1L;
public TestManagedBean() {}
#Override
public List<ProductUtils> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, Object> filters) {
// Put some logic here like setting total rows for LazyDataModel - setRowCount(10)
return service.constructor(first, pageSize); //Use filters and sort meta whenever necessary.
}
}
But this is also too unmaintainable, if I need to access more or less fields from the database at some later time at a different place that requires creating a new class or adding a new constructor (constructor overloading in the existing class) to the existing class which in turn requires to check carefully the actual and formal parameters of the constructor method to see, if they match in number, order and type precisely that often makes me blind.
I hope, there should be some better ways that allow us to tackle such situations in a precise way.
Parameterized constructor(s) in the existing entity classes, if used instead (without creating a new class like ProductUtils, in this case) may cause problems while implementing web services (JAX-WS) in the application (if needed). Therefore, I never tend to use parameterized constructors of entity classes anywhere.

Using a lookup table using google guava

I am new to Java. I have a requirement of holding a lookup table in memory(Abbreviations and their expansions). I was thinking of using Java Hash map. But I want to know if that really is the best approach.
Also, If there are any equivalent libraries in Google Guava, for the same requirement.
I want it to me optimized and very efficient w.r.t time and memory
Using Maps
Maps are indeed fine for this, as used below.
Apparently, it's a bit early for you to care that much about performance or memory consumption though, and we can't really help you if we don't have more context on the actual use case.
In Pure Java
final Map<String, String> lookup = new HashMap<>();
lookup.put("IANAL", "I Ain't A Lawyer");
lookup.put("IMHO", "In My Humble Opinion");
Note that there are several implementations of the Map interface, or that you can write your own.
Using Google Guava
If you want an immutable map:
final Map<String, String> lookup = ImmutableMap.<String, String>builder()
.put("IANAL", "I Ain't A Lawyer")
.put("IMHO", "In My Humble Opinion")
.build();
Retrieving Data
Then to use it to lookup an abbreviation:
// retrieval:
if (lookup.containsKey("IMHO")) {
final String value = lookup.get("IMHO");
/* do stuff */
}
Using Enums
I was speaking of alternatives...
If you know at coding time what the key/value pairs will be, you may very well be better off using a Java enum:
class Abbrevations {
IANAL ("I Ain't A Lawyer")
IMHO ("In My Humble Opinion");
private final String value;
private Abbreviations(final String value) {
this.value = value;
}
public String getValue() {
return (value);
}
}
You can then lookup values directly, ie either by doing this:
Abbreviations.IMHO.getValue()
Or by using:
Abbreviations.valueOf("IMHO).getValue()
Considering where you seem to be in your learning process, I'd recommend you follow the links and read through the Java tutorial and implement the examples.

Using *.resx files to store string value pairs

I have an application that requires mappings between string values, so essentially a container that can hold key values pairs. Instead of using a dictionary or a name-value collection I used a resource file that I access programmatically in my code. I understand resource files are used in localization scenarios for multi-language implementations and the likes. However I like their strongly typed nature which ensures that if the value is changed the application does not compile.
However I would like to know if there are any important cons of using a *.resx file for simple key-value pair storage instead of using a more traditional programmatic type.
There are two cons which I can think of out of the blue:
it requires I/O operation to read key/value pair, which may result in significant performance decrease,
if you let standard .Net logic to resolve loading resources, it will always try to find the file corresponding to CultureInfo.CurrentUICulture property; this could be problematic if you decide that you actually want to have multiple resx-es (i.e. one per language); this could result in even further performance degradation.
BTW. Couldn't you just create helper class or structure containing properties, like that:
public static class GlobalConstants
{
private const int _SomeInt = 42;
private const string _SomeString = "Ultimate answer";
public static int SomeInt
{
get
{
return _SomeInt;
}
}
public static string SomeString
{
get
{
return _SomeString;
}
}
}
You can then access these properties exactly the same way, as resource files (I am assuming that you're used to this style):
textBox1.Text = GlobalConstants.SomeString;
textBox1.Top = GlobalConstants.SomeInt;
Maybe it is not the best thing to do, but I firmly believe this is still better than using resource file for that...

Resources