what are Void(not void), Optional data types. where do we exactly use them?

So what am I supposed to return if the return type of a function has to be Void?

Use return null. Void can’t be instantiated and is merely a placeholder for the Class<T> type of void.

What’s the point of Void?

As noted above, it’s a placeholder. Void is what you’ll get back if you, for example, use reflection to look at a method with a return type of void. (Technically, you’ll get back Class<Void>.) It has other assorted uses along these lines, like if you want to parameterize a Callable<T>.

Now Optional

Java 8 comes with a new Optional type, similar to what is available in other languages.

What is the Optional type?

Optional is a new container type that wraps a single value, if the value is available. So it’s meant to convey the meaning that the value might be absent. Take for example this method:

1
2
3
public Optional<Customer> findCustomerWithSSN(String ssn) { 
...
}

Returning Optional adds explicitly the possibility that there might not be a customer for that given social security number.

This means that the caller of the method is explicitly forced by the type system to think about and deal with the possibility that there might not be a customer with that SSN.

The caller will have to to something like this:

1
2
3
4
5
6
7
8
9
Optional<Customer> optional = findCustomerWithSSN(ssn);
if (optional.isPresent()) {
    Customer customer = maybeCustomer.get();
    ... use customer ...
}
else {
    ... deal with absence case ...
}

Or otherwise provide a default value:

1
Long value = findOptionalLong(ssn).orElse(0L);

This use of optional is somewhat similar to the more familiar case of throwing checked exceptions. By throwing a checked exception, we use the compiler to enforce callers of the API to somehow handle an exceptional case.

What is Optional trying to solve?

Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing.

If Optional was there since the beginning, most libraries and applications would likely deal better with missing return values, reducing the number of null pointer exceptions and the overall number of bugs in general.

How should Optional be used then?

Optional should be used as the return type of functions that might not return a value.

What is Optional not trying to solve

Optional is not meant to be a mechanism to avoid all types of null pointers. The mandatory input parameters of methods and constructors still have to be tested for example.

Like when using null, Optional does not help with conveying the meaningof an absent value. In a similar way that null can mean many different things (value not found, etc.), so can an absent Optional value.

The caller of the method will still have to check the javadoc of the method for understanding the meaning of the absent Optional, in order to deal with it properly.

Also in a similar way that a checked exception can be caught in an empty block, nothing prevents the caller of calling get() and moving on.

What is wrong with just returning null?

The problem is that the caller of the function might not have read the javadoc for the method, and forget about handling the null case.

This happens frequently and is one of the main causes of null pointer exceptions, although not the only one.

How should Optional NOT be used?

Optional is not meant to be used in these contexts, as it won’t buy us anything:

  • in the domain model layer (not serializable)
  • in DTOs (same reason)
  • in input parameters of methods
  • in constructor parameters

How does Optional help with functional programming?

In chained function calls, Optional provides method ifPresent(), that allows to chain functions that might not return values:

1
2
findCustomerWithSSN(ssn).ifPresent(() -> 
    System.out.println("customer exists!"));

what is wrong with singleton. Singleton vs global Variable

http://programminglarge.com/singleton-design-pattern-vs-global-variable/

The Singleton design pattern has the distinction of being not only one of the simplest design patterns, but also ironically one of the most controversial. Much of the controversy stems from a failure to fully appreciate the consequences of using the pattern. The principle problem with the pattern is that it introduces global state into a program. Programmers that don’t recognize this may unwittingly use the pattern in situations where there are other, more appropriate design alternatives.

To understand the potential negative consequences associated with improper use of the Singleton design pattern, consider two designs for a class that encapsulates an integer.

The design on the left declares a global variable of type S. The design on the right implements class S as a singleton. Most programmers, even if they don’t fully understand all the reasons why, know to avoid global variables whenever possible. So, is the design on the right significantly better than the design on left because it avoids the use of a global variable? The short answer is no. While the design on the right avoids the use of a global variable per se, it still introduces global state, and it’s the consequences of global state that makes global variables so unpopular.

one of the main drawbacks with declaring a class as a singleton (and global variables as well) is that it can introduce hidden dependencies that weaken modularity. Figure 3 shows an example of how shared access to a singleton can create implicit coupling between two modules.

 

In a well modularized system you can study or test one module independent of others. Ideally, in order to study or test module A in the example above, you shouldn’t have to look beyond the borders of module A. However, because module A accesses global state in singleton S, you also have to be aware of code in other modules that update this global state. If you want to understand method f() in module A you also have to inspect the code in method h() in module B because h() modifies global state accessed by f(). Notice that the dependency goes beyond the interface to module B. You can’t simply study the interface of h() because global state is updated as a side-effect of calling h(). You have to study the detailed implementation of h().

Weakened modularity also makes testing more difficult. In the following code fragment, the class PaymentService is implemented as a singleton. This design makes it hard to test the routine checkout() in isolation. Any tests ran on the routine checkout() are going to effect whatever instance of PaymentService is available. Running a test on checkout() is likely to leave the system in a different state. This can cause havoc with test case ordering, repeatability, debugging, etc.

 

Given the magnitude of the liabilities associated with the Singleton design pattern, you should approach the declaration of a singleton as you would the declaration of a global variable and exhaust all other design alternatives before settling for a singleton.

 

 

 

Singleton in clustered /Distributed Env

In a multiple JVM’s environment, each of them will have their own copy of the singleton object which can lead to multiple issues specially in a clustered environment where the access to the resource needs to be restricted and synchronized.

To achieve clustering across multiple JVM’s, one can use multiple techniques (JMS, DB, Custom API, 3rd party tools), but each of them have an impact on the business logic.

  • Application server’s also provide some level of custom API’s to circumvent this problem.
  •  Terracotta, Oracle Coherence are good options. These work on the concept of providing an in memory replication of objects across JVMs in effect providing you singleton view  or making use of any of the cluster-aware cache provider’s like Swarm Cache or JBoss TreeCache should work as cache entries are singletons and clustering is built in.
  • Also, there is product called JGroups – which uses mulch-cast communication (TCP/UDP).  It allows to form a group and Applications (JVM’s) can participate and JGroups will send messages to everyone in the group so that they can be in sync.
  • JBoss has has Singleton Service ( based on MBeans) which is meant to solve this problem. Check hereand here
  • Weblogic has the concept of Singleton Service – where only instance runs within the cluster and all clients will look up to the same instance.
  • WebSphere supports the concept of singleton across cluster in the WebSphere😄 version of the application server as the partition facility – ObjectGrid