New We are sorting MAX channels into categories and territories. Read the news
Public channel ID 72002027903583

Java

Channels in category
2 102
This channel's rank
№ 223
Open category →
Worldwide
Open in MAX

Posts for the period

By reactions

Search and the whole feed — after free registration. Custom dates — with a subscription; the channel owner sees them for free. Sorting by reactions — with a subscription. Sign up

Loading…

Простой LRU-кеш в Java без дополнительных библиотек
LRU удаляет запись, к которой дольше всего не обращались. Для небольшого кеша достаточно LinkedHashMap:
import java.util.LinkedHashMap;
import java.util.Map;

class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;

LruCache(int capacity) {
super(16, 0.75f, true);
if (capacity <= 0) {
throw new IllegalArgumentException(
"capacity must be positive"
);
}
this.capacity = capacity;
}

@Override
protected boolean removeEldestEntry(
Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
Третий аргумент true включает порядок по обращениям: успешный get() переносит запись в конец. После добавления новой записи removeEldestEntry() позволяет удалить первую, если лимит превышен.
var cache = new LruCache<String, Integer>(2);

cache.put("A", 1);
cache.put("B", 2);
cache.get("A"); // Теперь B использовали давнее
cache.put("C", 3); // Удалится B

System.out.println(cache.keySet()); // [A, C]
Лимит задаётся числом записей, а не объёмом памяти. TTL здесь нет, и кеш не потокобезопасен. Более того, даже get() может менять внутренний порядок, поэтому параллельные чтения тоже требуют синхронизации.
Views: 67
Go to post Open in MAX Report an inaccuracy
Spring: граница транзакции должна охватывать бизнес-операцию целиком.

Например, перевод денег – это списание с одного счёта и зачисление на другой. Разместите оба действия в методе сервиса:
@Service
@RequiredArgsConstructor
public class TransferService {
    private final AccountRepository accounts;

    @Transactional
    public void transfer(Long fromId, Long toId,
                         BigDecimal amount) {
        var from = accounts.findById(fromId).orElseThrow();
        var to = accounts.findById(toId).orElseThrow();

        from.withdraw(amount);
        to.deposit(amount);
    }
}
Оба изменения фиксируются вместе. Если при зачислении возникнет исключение, вызывающее откат, списание тоже отменится.

Контроллеру остаётся проверить входные данные и вызвать сервис. Бизнес-правила находятся рядом с операцией, которую защищает транзакция.

Два нюанса:

- По умолчанию Spring откатывает транзакцию при `RuntimeException` и `Error`. Для checked exceptions можно настроить rollbackFor.
- В стандартном proxy-режиме вызов метода через `this` не активирует `@Transactional`.

Транзакция также не заменяет защиту от конкурентных изменений: для денежных операций отдельно продумайте блокировки или контроль версий.
Views: 98
Go to post Open in MAX Report an inaccuracy
VKontakte Telegram Odnoklassniki
Favorites at datool.ru

Follow the channel in your account

Sign up at datool.ru to add the channel “Java” to favorites and track its metrics.

Sign up
For channel owners

Verify your channel

Sign in or sign up at datool.ru, then add our bot to the channel following the instructions in your account. Once ownership is verified, the lock disappears and channel management becomes available.

Sign in or sign up

Report an inaccuracy

Describe what needs fixing. If you have a source, add a link.

You are leaving datool.ru

The link leads to an external website. datool.ru is not responsible for its content — check the address before entering passwords or payment details.

Redirecting in 10 s

Go