Skip to main content
Java小技巧

如何编写更健壮更好的java代码?这里面整理收集一些在java开发过程中我们需要注意的一些点或者说是技巧,从而提高代码的质量以及我们的工作效率。

Springboot

Ignore Null Fields with Jackson

Springboot中默认序列化Json的框架就是jackson了,这里面介绍在Springboot项目中如何忽略null字段

  • 全局

springboot配置和java代码都可以实现全局忽略null的功能

  • 类级别

huhxOriginalAbout 12 minjavaTips
DelayQueue

使用

public class DelayQueueMain {
    public static void main(String[] args) {
        var queue = new DelayQueue<DelayedUser>();
        var executorService = Executors.newFixedThreadPool(2);

        executorService.execute(() -> {
            for (int i = 0; i < 3; i++) {
                var delayedUser = new DelayedUser("name-" + i, new Random().nextInt(2000));
                queue.put(delayedUser);
                System.out.println(Thread.currentThread().getName() + " put user: " + delayedUser.name() + ", avaibleTime: " + delayedUser.avaibleTime());
                sleep(1);
            }
        });

        executorService.execute(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    var delayedUser = queue.take();
                    System.out.println(Thread.currentThread().getName() + " take user: " + delayedUser.name() + ", avaibleTime: " + delayedUser.avaibleTime());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        executorService.shutdown();
    }

    static void sleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

record DelayedUser(String name, long avaibleTime) implements Delayed {

    DelayedUser(String name, long avaibleTime) {
        this.name = name;
        this.avaibleTime = System.currentTimeMillis() + avaibleTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(avaibleTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.avaibleTime - ((DelayedUser) o).avaibleTime);
    }
}

huhxLess than 1 minutejavaConcurrency-CollectionConcurrency