ThreadLocal vs Parameter Passing - What to choose in interface design?

I already read an interesting discussion on the next topic about ThreadLocal and its use.

These questions concern development timing. My script is like this

If I have a value object in a web application that you might need to use inside a single thread in almost all steps. I can present two options for the design of the interface, for example below

Approach # 1 Using method parameter passing.

I have so far focused on developing an interface that can have methods with object value interface parameters.

For example:

public interface SomeDataProcessorInterface {

public void processSomething(SomeValueObjectInterface vo);

}

public interface SomeValueObjectInterface extends Serializable {}

Aproach # 2 Using ThreadLocal

In this approach, I can have an interface without a method parameter and just create a static class to access my value objects using threadlocal.

For example:

public interface SomeDataProcessorInterface {

public void processSomething();

}

public interface SomeValueObjectInterface extends Serializable {}

public Class StaticClass {

    private static ThreadLocal<SomeValueObjectInterface> threadLocalVO = new ThreadLocal<SomeValueObjectInterface>();

     public static ThreadLocal getThreadLocal() {
        return threadLocal;
      }

Which approach is better? and why?

Which of these implementations will have less chance of a memory leak?

Which of these implementations will be useful for the Java Garbage Collector?

I read a few points in another thread, but I still haven't figured out which approach is better if I start from scratch.

+4
source share
3 answers

.

SomeValueObjectInterface - , ( ) , (, ), -, ThreadLocal.

, ThreadLocal finally, ( ).

GC, , ThreadLocal, eden.

+2

- ThreadLocal, 99.99999% . ThreadLocal - , ( , , , ), , . " ", ( , , , , ). , , .

a ShapeCollection, DrawAll, Draw . , "", , , , -, . Shape , Draw asPlaceHolder, ShapeCollection DrawAll . , Shape , ShapeCollection .

fancy shape objects Draw , " " , . , , , , , . , Draw , . , DrawingOptions, , DrawAll, , , DrawAll Draw - , .

+2

C, static TheadLocalyou risk losing memory if you forget to delete an item. You can always avoid this by deleting the item before returning from your method. I would not recommend this approach.

Your first approach is already thread safe because it is worth it since the parameter will be local only for this method. Use this one.

+1
source

All Articles