Uno scrittoio digitale …

6 giugno 2017

Enterprisify your Java Class Names!

Archiviato in: Senza categoria — Tag: — admin @ 18:26

java class name

29 dicembre 2016

NPE Java8 Stream

Archiviato in: code — Tag:, , — admin @ 17:40

Volendo convertire una lista in una mappa … c’è un metodo sicuramente sbagliato:

	final Map data = new HashMap<>();
	data.put(1, "uno");

		IntStream.rangeClosed(1, 2).boxed()
				(map, i) -> map.put(i, data.get(i)),

	//questa implementazione si basa sul metodo HashMap.merge (che lancia exception)
		IntStream.rangeClosed(1, 2).boxed()
				i -> i, i -> data.get(i)

ottengo a console:

{1=uno, 2=null}
Exception in thread "main" java.lang.NullPointerException
	at java.util.HashMap.merge(
	at java.util.Spliterator$OfInt.forEachRemaining(

24 maggio 2016


Archiviato in: code — Tag:, , , , — admin @ 09:18

It’s like JSON. but fast and small.

21 maggio 2015

MapDB (java library)

Archiviato in: java — Tag:, , , — admin @ 20:24

MapDB is embedded database engine. It provides java collections backed by disk or memory database store. MapDB has excellent performance comparable to java.util.HashMap and other collections, but is not limited by GC. It is also very flexible engine with many storage backend, cache algorithms, and so on. And finally MapDB is pure-java single 400K JAR and only depends on JRE 6+ or Android 2.1+.

What for?
> In-memory cache with expiration based on time-to-live or maximal size, Redis or EZCache replacement
> Huge indexes
> Persistent data model
> Alternative memory model if you are limited by GC

10 ottobre 2014


Archiviato in: code, java — Tag:, , — admin @ 17:42

hanno sviluppato un casino di progetti … come si può vedere qua

17 luglio 2013


Archiviato in: java, oracle — Tag:, , , — admin @ 22:22

The javadoc says this:

“Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

If your application or (if you are talking about request threads) container uses a thread pool that means that threads don’t die. If necessary, you would need to deal with the thread locals yourself. The only clean way to do this is to call the ThreadLocal.remove() method.

There are two reasons you might want to clean up thread locals for threads in a thread pool:

to prevent memory (or hypothetically resource) leaks, or
to prevent accidental leakage of information from one request to another via thread locals.

Thread local memory leaks should not normally be a major issue with bounded thread pools since any thread locals are likely to get overwritten eventually; i.e. when the thread is reused. However, if you make the mistake of creating a new ThreadLocal instances over and over again (instead of using a static variable to hold a singleton instance), the thread local values won’t get overwritten, and will accumulate in each thread’s threadlocals map. This could result in a serious leak.

private void cleanThreadLocals() {
        try {
            // Get a reference to the thread locals table of the current thread
            Thread thread = Thread.currentThread();
            Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            Object threadLocalTable = threadLocalsField.get(thread);

            // Get a reference to the array holding the thread local variables inside the
            // ThreadLocalMap of the current thread
            Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
            Field tableField = threadLocalMapClass.getDeclaredField("table");
            Object table = tableField.get(threadLocalTable);

            // The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
            // is a reference to the actual ThreadLocal variable
            Field referentField = Reference.class.getDeclaredField("referent");

            for (int i=0; i < Array.getLength(table); i++) {
                // Each entry in the table array of ThreadLocalMap is an Entry object
                // representing the thread local reference and its value
                Object entry = Array.get(table, i);
                if (entry != null) {
                    // Get a reference to the thread local object and remove it from the table
                    ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
        } catch(Exception e) {
            // We will tolerate an exception here and just log it
            throw new IllegalStateException(e);

A good place to do such cleanup is ServletRequestListener.requestDestroyed().

3 ottobre 2012

Difference between ConcurrentHashMap and Collections.synchronizedMap

Archiviato in: java — Tag: — admin @ 19:05

read me

18 settembre 2012

Guice AssistedInject

Archiviato in: java — Tag:, , — admin @ 22:38
public class GuiceModule extends AbstractModule {
	protected void configure() {


		install(new FactoryModuleBuilder()
	    	.implement(Payment.class, RealPayment.class)


public interface AuthService {

public class RealAuthService implements AuthService {

public interface Payment {
	void pay(BigDecimal amount);

public class RealPayment implements Payment {
	public RealPayment(AuthService authService, @Assisted BigDecimal amount) {
		System.err.println("create RealPayment with args");
		System.err.println("authService: " + authService);
		System.err.println("amount: " + amount);

	public void pay(BigDecimal amount) {


public interface PaymentFactory {
	Payment create(BigDecimal amount);

public static void main(String[] args) {
	final Injector injector = Guice.createInjector(new GuiceModule());
	final PaymentFactory paymentFactory = injector.getInstance(PaymentFactory.class);

	System.err.println("create payment: " + paymentFactory.create(BigDecimal.TEN));

23 gennaio 2012


Archiviato in: java — Tag:, , — admin @ 22:44

Constructors are tricky in Java, and that’s exposed in AspectJ. Here are some rules of thumb I use:

* If you want the join point on the “outside” of object creation, use:

after() returning (Foo f): call( { … }

you might be tempted to use “this” or “target” to expose the new object, but remember
that if you’re on the “outside” of object creation, the object itself might not be
created yet… it only exists “on the way out”, when you return the object.

* If you want the join point inside a particular constructor, use:

after(Foo f) returning: this(f) && execution( { … }

remember, though, that if you use “before” advice here, the body of the constructor
will not have run, and so the object may be somewhat uninitialized.

* In the rare case that there are all sorts of constructors for the object
that call each other with this(…) and you want exactly one join point
for each initialization of Foo, regardless of the path of constructors it takes,
then use:

after(Foo f) returning: this(f) && initialization( { … }


9 ottobre 2011

Java Observer Pattern

Archiviato in: code, java, oracle — Tag:, — admin @ 12:58

In relazione al pattern, java fornisce delle API già pronte all’uso:


Mitico :D

14 maggio 2011


Archiviato in: sapere è potere — Tag:, , — admin @ 15:37

ottimo sito per la condivisione di informazioni sulle aziende … sopo

7 maggio 2011

Framework ad eventi

Archiviato in: code, java — Tag:, , , , — admin @ 11:51

oracle adf

13 marzo 2011

Domanda frequente

Archiviato in: java — Tag:, — admin @ 12:44

Vi è mai capitato di usare una classe di un package non scritto da voi … magari senza documentazione o test ?
Bene, invece di usare l’approccio WTF … esiste un mitico sito che ci aiuta a capire come si usa un’API

29 gennaio 2011

Another Java Proxy

Archiviato in: java — Tag:, , , , — admin @ 14:39
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TraceProxy implements java.lang.reflect.InvocationHandler {

	private Object object;

	public static Object createProxyFor(Object object) {
		final TraceProxy traceProxy = new TraceProxy(object);
		System.out.println("\ntraceProxy = " + traceProxy);

		return Proxy.newProxyInstance(

	private TraceProxy(Object object) {
		this.object = object;

	public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
		System.err.println("traceProxy = " + this);
		System.err.println("m = " + m);
		System.err.println("args = " + args);

		if (args != null) {
			for (Object object : args) {

		return m.invoke(object, args);

	public static void main(String[] args) {
		CharSequence cs = (CharSequence) TraceProxy.createProxyFor("abcdefghilmnopqrstuvz");

		System.out.println("\ncall charAt");
		System.out.println("charAt result is '" + cs.charAt(2) + "'\n");

		//sleep ... altrimenti l'output non è chiaro
		try { Thread.sleep(10); } catch (InterruptedException e) { }

		System.out.println("call length");
		System.out.println("length result is '" + cs.length() + "'");

27 gennaio 2011

Pattern in Java

Archiviato in: java — Tag: — admin @ 14:33

Qui un primo articolo con esempi semplici.

25 novembre 2010


Archiviato in: code, java — Tag:, — admin @ 23:20


4 novembre 2010


Archiviato in: java — Tag:, — admin @ 20:57


quante alternative !!?

21 ottobre 2010

struts 2 i18n

Archiviato in: java — Tag:, — admin @ 14:35

un paio di link utili …


19 ottobre 2010

Guice 4 Android

Archiviato in: code, java — Tag:, , , — admin @ 21:39

Non sò come e se funziona … ma è sicuramente da provare … roboguice

Guice 2.0

Archiviato in: code, java — Tag:, , , , , — admin @ 21:36

La versione 2.0 aggiunge molte funzionalità interssanti al framework


Articoli precedenti »

Funziona con WordPress