10 Haziran 2022 Cuma

jdb komutu

-attach seçeneği
Örnek
Şöyle yaparız
$ jdb -attach 127.0.0.1:8000
> Initializing jdb ...
Örnek
Eğer uygulama çalışmıyorsa veya debug modunda çalıştırılmadıysa hata olarak şunu alırız
$ jdb -attach localhost:8000
java.net.ConnectException: Connection refused (Connection refused)
-sourcepath seçeneği
Açıklaması şöyle
The sourcepath argument allows you to provide the colon-separated list of paths to look for the sources. You can provide not only the sources of your application but also the sources of the libraries you use, to be able to easily follow their source code during the debugging session.
Örnek
Şöyle yaparız
$ jdb -attach localhost:8000 -sourcepath ~/dev/remote/src/main/java/
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
>


jinfo komutu - Çalışan JVM Hakkında Bilgi Verir

Giriş
jps ile çalışan uygulamaları buluruz. Daha sonra jinfo ile bu process hakkında bilgi alabiliriz.

-flags seçeneği
JVM parametrelerini gösterir. Şöyle yaparız
jinfo -flags <pid>
-sysprops seçeneği
JVM'e geçilen system properties bilgilerini gösterir. Şöyle yaparız
jinfo -sysprops <pid>




30 Mayıs 2022 Pazartesi

Swing MaskFormatter Sınıfı

Giriş
Şu satırı dahil ederiz. JFormattedTextField ile birlikte kullanılır
import javax.swing.text.MaskFormatter;
Örnek
Şöyle yaparız
JFormattedTextField customerId = new JFormattedTextField(new MaskFormatter("UUU_UUU"));
Mask Örnekleri
UUU_UUU
########-#### - Date
#.# - Product Version

26 Mayıs 2022 Perşembe

JUnit Pioneer İle Birim Testi

Giriş
System.getProperty() şeklindeki çağrıları test etmeyi kolaylaştıyor. Bence kullanması System Stubs'tan çok daha kolay

Gradle
Şöyle yaparız
testImplementation 'org.junit-pioneer:junit-pioneer:1.7.0'
Örnek
Şöyle yaparız
@Test
@ClearSystemProperty(key = "some key")
@SetSystemProperty(key = "another key", value = "new value")
void test() {
  assertNull(System.getProperty("some key"));
  assertEquals("new value", System.getProperty("another key"));
}



19 Mayıs 2022 Perşembe

Helidon

Giriş
Açıklaması şöyle
Helidon is a set of libraries for microservices. It is created and maintained by Oracle. To run it, we need at least Java 11. The latest release introduces support for Java 17. We can write code with Java and Kotlin as well. Interestingly, it comes in two flavors: Helidon SE and Helidon MP.
...
Both may be compiled into native images using GraalVM, resulting in a faster startup time and lower memory consumption. However, the SE profile consumes fewer resources than MP.
İki türevi var. Her ikisi de GraalVM ile çalışıyor
1. Helidon SE
2. Helidon MP

1. Helidon SE
Açıklaması şöyle
Helidon SE is a small toolkit that supports the most recent Java SE features, including reactive streams, asynchronous and functional programming, and APIs with a fluid design. Helidon SE offers GraalVM native files for low storage use and flash -like launch. Helidon SE’s REST framework is based on Netty and provides a simplistic API for session handling.
Açıklaması şöyle
Helidon SE is a toolkit providing reactive streams, asynchronous and functional programming, and fluent-style APIs. It offers a reactive API for streams, messaging, and databases. You may create web endpoints based on GraphQL, gRPC, WebSockets, and HTTP server technologies. Next, we can secure them using a dedicated security add-on. And, at the end, we can spice it with a pinch of metrics, health checks, tracing, and documentation with OpenAPI.
2. Helidon MP
Açıklaması şöyle
On the other hand, Helidon MP is an implementation of MicroProfile specification. Among the features mentioned for the SE profile, you can find here support for JPA, RESTful services, security with JWT, and long-running actions based on SAGA patterns. Furthermore, this version is meant to run in the cloud; we can deploy an application on OCI or Kubernetes.

Both may be compiled into native images using GraalVM, resulting in a faster startup time and lower memory consumption. However, the SE profile consumes fewer resources than MP.

3 Mayıs 2022 Salı

RAbbitMQ API

Channel Sınıfı
Şu satırı dahil ederiz. Bu sınıfın basicPublish(), basicConsume() metodları ile mesaj gönderilir ve alınır
import com.rabbitmq.client.Channel;
constructor
Örnek
Şöyle yaparız
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");

Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
basicConsume metodu
Örnek
Şöyle yaparız
DeliverCallback deliverCallbackDlx = (consumerTag, delivery) -> {
  String routingKey = delivery.getEnvelope().getRoutingKey();
  String message = new String(delivery.getBody(), StandardCharsets.UTF_8);

  System.out.println(" [x] Received WITH DLX! '" + routingKey + "':'" + message + "'");

  channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
};

channel.basicConsume("tickets_dlx", false, deliverCallbackDlx, consumerTag -> {});
basicPublish metodu
Örnek
Açıklaması şöyle
The following shows how RabbitMQ’s Java publisher sets the TTL of a message which can reside in the queue for at most 60 seconds:
Şöyle yaparız
byte[] messageBodyBytes = "Hello, world!".getBytes();
AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                                   .expiration("60000")
                                   .build();
channel.basicPublish("my-exchange", "routing-key", properties, messageBodyBytes);
Örnek
Şöyle yaparız
channel.basicPublish("tickets", "payment_is_done", null,
  paymentInfo.toString().getBytes(StandardCharsets.UTF_8));
exchangeDeclare metodu
Örnek
Şöyle yaparız
channel.exchangeDeclare("tickets", "direct");
queueDeclare metodu
Örnek
Şöyle yaparız. Burada kuyruk için dead letter exchange de tanımlanıyor
Map<String, args = new HashMap<>()
{
  {
    put("x-max-length", 10);
    put("x-message-ttl", 5000);
    put("x-dead-letter-exchange", "tickets_dlx";
    put("x-dead-letter-routing-key", "payment_is_done");
  }
};

channel.queueDeclare("TICKETS_AFTER_APPROVING_PAYMENT", 
  true, //Durable
  false,//Exclusive 
  false, //Auto delete
  args);
channel.queueBind("TICKETS_AFTER_APPROVING_PAYMENT", "tickets", "payment_is_done");



5 Nisan 2022 Salı

AtomicIntegerArray Sınıfı

Giriş
Şu satırı dahil ederiz
import java.util.concurrent.atomic.AtomicIntegerArray;
AtomicLongArray sınıfı da benzer işlev görür. Açıklaması şöyle
Provides atomic operations for arrays of int variables. It has the same methods as AtomicInteger but has an “index” in its signature. You can not change the size of the array after the AtomicIntegerArray was created.

Kullanım Durumu
Açıklaması şöyle
Noncompliant Code Example (Arrays)
Values assigned to an array element by one thread—for example, by calling setFirst()—might not be visible to another thread calling getFirst() because the volatile keyword guarantees safe publication only for the array reference; it makes no guarantee regarding the actual data contained within the array.

This problem arises when the thread that calls setFirst() and the thread that calls getFirst() lack a happens-before relationship. A happens-before relationship exists between a thread that writes to a volatile variable and a thread that subsequently reads it. However, setFirst() and getFirst() read only from a volatile variable—the volatile reference to the array. Neither method writes to the volatile variable.

Compliant Solution (AtomicIntegerArray)
To ensure that the writes to array elements are atomic and that the resulting values are visible to other threads, this compliant solution uses the AtomicIntegerArray class defined in java.util.concurrent.atomic.
getAndIncrement metodu
Örnek
Şöyle yaparız
final int arrayLength = 5;
AtomicIntegerArray atomicIntArray = new AtomicIntegerArray(arrayLength);

Runnable incrementTask = () -> {
  for (int i = 0; i < arrayLength; i++) {
    int previousValue = atomicIntArray.getAndIncrement(i);
    System.out.println("Incremented index " + i + ": " + previousValue 
      + " to " + (previousValue + 1));
  }
};

Thread thread1 = new Thread(incrementTask);
Thread thread2 = new Thread(incrementTask);

thread1.start();
thread2.start();

try {
  thread1.join();
  thread2.join();
} catch (InterruptedException e) {
  e.printStackTrace();
}

System.out.println("Final Array: " + atomicIntArray.toString());
get ve set metodu
Örnek
Şöyle yaparız
final class Foo {
  private volatile int[] arr = new int[20];
 
  public int getFirst() {
    return arr[0];
  }
 
  public void setFirst(int n) {
    arr[0] = n;
  }
 
  // ...
}

class Foo {
  private final AtomicIntegerArray atomicArray = new AtomicIntegerArray(20);
 
  public int getFirst() {
    return atomicArray.get(0);
  }
 
  public void setFirst(int n) {
    atomicArray.set(0, 10);
  }
 
  // ...
}