24 Kasım 2022 Perşembe

Jakarta EE Concurrency @Lock

Örnek
Şöyle yaparız
//Provides locking semantics for CDI Beans – especially useful for ApplicationScoped
//Semantics would be similar to EJB Locks
@ApplicationScoped
public class CDIBean {

  @Lock(LockType.READ) 
  public void doReadMany(){}

  @Lock(LockType.WRITE) 
  public void doOneWriter() {}

}

Jakarta EE Concurrency @MaxConcurrency

Örnek
Şöyle yaparız
//Limits through Semaphore the number of threads that can execute a method or all
//methods concurrently.
@ApplicationScoped
public class CDIBean {

  @MaxConcurrency(2) 
  public void maxTwoThreadsMethod(){};

  @MaxConcurrency(10) 
  public void maxUseofAPI(){}

}

Jakarta EE Concurrency

Giriş
Şu anotasyonlar kullanılabilir

Ayrıca şu sınıflar var
ManagedThreadFactory

Ayrıca Deployable Managed Objects olarak şunlar var
ContextServiceDefinition
ManagedExecutorDefinition
ManagedScheduledExecutorDefintion
ManagedThreadFactoryDefinition

Maven
Örnek - Jakarta 8
Şu satırı dahil ederiz
<dependency>
<groupId>jakarta.enterprise.concurrent</groupId>
<artifactId>jakarta.enterprise.concurrent-api</artifactId>
<version>1.1.2</version>
</dependency>
Örnek - Jakarta 9
Şu satırı dahil ederiz
<dependency>
<groupId>jakarta.enterprise.concurrent</groupId>
<artifactId>jakarta.enterprise.concurrent-api</artifactId>
<version>2.0</version>
</dependency>
Örnek - Jakarta 10
Şu satırı dahil ederiz
<dependency>
<groupId>jakarta.enterprise.concurrent</groupId>
<artifactId>jakarta.enterprise.concurrent-api</artifactId>
<version>3.0.2</version>
</dependency>

8 Kasım 2022 Salı

JCache - JSR 107

Giriş
İlk olarak 2011 yılında Java EE 7 ile ortaya çıktı. Açıklaması şöyle
The JVM ecosystem has an official Cache API, known as JCache, or JSR 107. It’s a specification with an API that describes four annotations, i.e., @CacheResult, @CachePut, @CacheRemove, and @CacheRemoveAll. Vendors are to implement the specification.

The Spring framework is pretty widespread in the JVM ecosystem. It also provides a caching API. Historically, it predates JCache. While different, the API is very similar to JCache’s. Spring offers out-of-the-box integration code for a couple of caches, while a couple of others do provide Spring integration.
Java Cache Providers
Liste şöyle. Bunların içinden sadece Guava ve Geode JCache desteği sunmuyor.
  1. Java Caching System
  2. Guava
  3. Caffeine
  4. Ehcache
  5. Infinispan
  6. Coherence Community Edition
  7. Ignite
  8. Geode
  9. Hazelcast
Spring vs JCache
Anotasyonlar şöyle

JCache API interfaces
Önemli sınıflar şöyle
1. javax.cache.CacheManager
2. javax.cache.Cache 
3. javax.cache.configuration.Configuration

JCache Annotations 
@CacheResult
@CachePut
@CacheRemove

CacheManager Arayüzü
Şu satırı dahil ederiz
import javax.cache.CacheManager;
Açıklaması şöyle
It enables us to establish, configure and close Caches.
Bu arayüzü gerçekleştiren sınıflardan birisi. İlgili notlarım burada
import com.hazelcast.cache.HazelcastCacheManager;
@CacheResult
Örnek
Şöyle yaparız
public class ServiceImpl {

  @Override
  @CacheResult(cacheName = ..., cacheKeyGenerator = DefaultObjectsCacheKeyGenerator.class)
  public Foo getObject(@CacheKey String userId, @CacheKey String customerId) {
    ...
  }
}



26 Eylül 2022 Pazartesi

Jakarta EE Extension Arayüzü

Örnek
Şöyle yaparız
import jakarta.enterprise.inject.spi.Extension;
public class StartupBeanExtension implements Extension { private final Set<Bean<?>> startupBeans = new LinkedHashSet<>(); <X> void processBean(@Observes ProcessBean<X> event) { if (event.getAnnotated().isAnnotationPresent(Startup.class) && event.getAnnotated().isAnnotationPresent(ApplicationScoped.class)) { this.startupBeans.add(event.getBean()); } } void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) { for (Bean<?> bean : startupBeans) { manager.getReference(bean, bean.getBeanClass(), manager.createCreationalContext(bean)) .toString(); } } }

6 Temmuz 2022 Çarşamba

Jakarta EE @PostConstruct Anotasyonu

Giriş
Şu satır dahil ederiz.
import javax.annotation.PostConstruct;
Yeni kodlarda şu satır dahil ederiz.
import jakarta.annotation.PostConstruct;
Spring'e ait gibi görünse de aslında bu bir Java anotasyonu. Şöyle yaparız.
public class Foo {
  ...

  @PostConstruct
  public void fooInit(){
    ...
  }

  public Foo() {
    ...
  }
}
Açıklaması şöyle
1. When the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.

2. this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.
Spring Birden Fazlan @PostConstruct Çalıştırabilir
Örnek
Şöyle yaparız
// Spring can also handle more than one method annotated with @PostConstruct, like this:
@PostConstruct
public void init() {
  log.info("1111 tests");
}

@PostConstruct
public void init2() {
  log.info("2222 tests");
}
Örnek - getter ve setter
Elimizde getter ve setter metodları olan bir sınıf olsun. Eğer constructor içinde application nesnesine erişmek istersek null pointer exception fırlatılır. Çünkü constructor metodu çalıştı ancak daha setter metodu çağrılmadı. Dolayısıyla constructor içine yazmayı düşünüdüğümüz kodu @PostConstruct olarak işaretli bir metoda taşımamız gerekir.
public class Foo {

  private String application;

  public String getApplication() {
    return application;
  }

  public void setApplication(String application) {
    this.application = application;
  }
  ...
}

5 Temmuz 2022 Salı

EJB @ConcurrencyManagement Anotasyonu

CONTAINER Managed
Açıklaması şöyle
If nothing else is specified, by default singleton session bean uses container managed concurrency. Further, if not specified, every business and timeout method have by default LockType.WRITE. Result is that there is not multiple threads concurrently executing methods in singleton and as consequence using regular java.util.HashMap is perfectly fine.
Örnek 
Şöyle yaparız
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Local;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import java.util.HashMap;
import java.util.Map;

@Singleton
@Local(MapsAndQueuesSingletonBeanLocal.class)
public class MapsAndQueuesSingletonBean implements MapsAndQueuesSingletonBeanLocal {

    private Map<String String> maps = new HashMap<>();
    
    @Override
    public String getMap(String key) {
        return maps.computeIfAbsent(key, k -> ...);
    }

}
Açıklaması şöyle
If nothing else is specified, by default singleton session bean uses container managed concurrency. Further, if not specified, every business and timeout method have by default LockType.WRITE. Result is that there is not multiple threads concurrently executing methods in singleton and as consequence using regular java.util.HashMap is perfectly fine.
BEAN Managed
Açıklaması şöyle
@Singleton in the default configuration is the perfect bottleneck. Only one thread a time can access a @Singleton instance.
The annotation @ConcurrencyManagement(ConcurrencyManagementType.BEAN) deactivates this limitation and makes a Singleton instance accessible from multiple threads:
Örnek 
Şöyle yaparız
import javax.ejb.Singleton;
import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import java.util.concurrent.ConcurrentHashMap;
import javax.ejb.ConcurrencyManagementType;

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Hits {

  private ConcurrentHashMap hits = null;
	
  @PostConstruct
  public void initialize() {
    this.hits = new ConcurrentHashMap();
  }
  //cache accessors omitted
}


Bean Validation @GroupSequence Anotasyonu

Örnek Elimizde şöyle bir kod olsun public class SampleRequest {   @NotNull   LocalDate startDate;   @NotNull   LocalDate endDate;   @AssertT...