Stéphane Millien
Stéphane Millien

Reputation: 3448

How to make an ExecutorService act as a LIFO

I have a client application in Java Swing which displays a list of pictures. Pictures are displayed with JLabel. The thumbnails are cached in a Firebird database and returned by a web-service Soap/MTOM.

Video of the behavior

I create all the Jlabel in a SwingWorker and retrieve the thumbnail in the paint method of the Jlabel (if icon not yet assigned). I am using an Java ExecutorService to call the web-services which return each thumbnail.

As you can see in the video, when I scroll down a big amount lines, I have to wait that all thumbnails in JLabel visible during scrolling are fetched.

The ExecutorService is instantiated like this:

ExecutorService executor = Executors.newFixedThreadPool(20);

The piece of code called from paint method when getIcon() == null is:

executor.execute(new FutureTask<Void>(() -> {
    var image = EdmWS.getInstance().getThumbnail(thumbnail.date, thumbnail.name, sizeThumbnail);
    label.setIcon(new ImageIcon(image));
    label.invalidate();
}, null));

Is there a way to have an executor working like a LIFO (last in first out) to get the thumbnails of displayed JLabel as soon as possible?


Thank for your comment, Executor Service with LIFO ordering

executor = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>() {

    private static final long serialVersionUID = 1L;

    @Override
    public boolean offer(Runnable e) {
        return super.offerFirst(e);
    }

    @Override
    public boolean offer(Runnable e, long timeout, TimeUnit unit) throws InterruptedException {
        return super.offerFirst(e, timeout, unit);
    }

    @Override
    public boolean add(Runnable e) {
        return super.offerFirst(e);
    }

    @Override
    public void put(Runnable e) throws InterruptedException {
        super.putFirst(e);
    }
});

do the job.

Upvotes: 1

Views: 26

Answers (0)

Related Questions